I am trying to implement an IP discoverer app for microchip platform. I am using GCDAsyncSocket to do this. IF I send a specific message, all devices of interest will respond with their network credentials.
With GCDAsyncSocket, If I use a specific IP, I can get a response. But I am not sure how to broadcast this message to all IPs in the network.
My Code: udpSocket = [[GCDAsyncUdpSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
- (void)setupSocket
{
NSError *error = nil;
if (![udpSocket bindToPort:0 error:&error])
{
[self logError:FORMAT(@"Error binding: %@", error)];
return;
}
if (![udpSocket beginReceiving:&error])
{
[self logError:FORMAT(@"Error receiving: %@", error)];
return;
}
[udpSocket enableBroadcast:YES error:&error];
if (error != nil)
{
NSLog(@"Error enableing broadcast: %@", [error description]);
return;
}
[self logInfo:@"Ready"];
}
- (IBAction)send:(id)sender
{
NSString *host = addrField.text;
NSError *error = nil;
NSData *data = [msg dataUsingEncoding:NSUTF8StringEncoding];
[udpSocket sendData:data toHost:host port:port withTimeout:-1 tag:tag];
[self logMessage:FORMAT(@"SENT (%i): %@", (int)tag, msg)];
tag++;
}
Now, how can I make it to send to all IPs instead of only one IP? In the original PC java app, I can see something like
socket = new DatagramSocket(30303);
socket.setBroadcast(true);
InetAddress address = InetAddress.getByName("255.255.255.255");
packet = new DatagramPacket(str.getBytes(),
str.length(), address, 30303);
socket.send(packet);
And I want to do the same on this app. Appreciate some help.
I have used the same socket library in my ios app for the same purpose (searching device on network) the code i have used was..
Calling sendata function of socket with NSData object will broadcast data to all the ip on the network listening on the given port.