GCDAsyncUdpSocket Socket Closes In between sending 255 packets

252 Views Asked by At

I have a module where I have to discover by sending a packets to the 255 IP addresses. eg. Connected IP : 192.188.2.1 then I have to send a packet changing the last value i.e.

var HOST = "192.188.2.1"
var arr = HOST.components(separatedBy: ".")
for i in 1 ..< 254
{
     dispatchGroup.enter()
     time += 0.005
     DispatchQueue.main.asyncAfter(deadline: .now() + time) {
        let obj = LPScanPacket()
         arr[3] = "\(i)"
         let str = arr.joined(separator: ".")
         SenderWrapper.sendLPPacket(lpPacket: obj, HOST: str)
         dispatchGroup.leave()
      }          
 }
 dispatchGroup.notify(queue: .main) {
      print("Completed sending ")
 }

But on sending this many packet it shows me error within udpSocketDidClose delegate method

Error Domain=NSPOSIXErrorDomain Code=65 "No route to host" UserInfo={NSLocalizedDescription=No route to host, NSLocalizedFailureReason=Error in send() function.}

Firstly why do I get this error, is there any alternative way I can achieve this result.

EDIT :

Try running this code, I am trying to get response from the device connected to the same router. To find the device IP I am using the above code. But the socket closes in between sometimes it works and sometime it doesn't I am not able to find the solution why it closes.

Thanks

1

There are 1 best solutions below

1
user3441734 On

A broadcast message is sent to all hosts on a network or subnetwork and is created by setting the node part of the IP address to all 1’s.

The error message you received is related to the fact, that broadcasts messages do not go through routers.

To be able to broadcast a datagram, the underlying socket must be in the broadcast mode. Run man setsockopt in your terminal for further reference.