Little problem with AsyncUdpSocket receiving data after connecting to broadcast instead of server

eemceebee picture eemceebee · Apr 26, 2011 · Viewed 8.4k times · Source

I have a problem with AsyncUdpSocket.

I used to connect to a server, send some data and get some response. Now since I do not know the actual address of the server I had to change my code and send the data to the broadcast address 255.255.255.255.

Here is my code :

NSString *bchost = @"255.255.255.255";
NSString *host = @"10.1.0.1";
int udpPort = 6001;

AsyncUdpSocket *udpSocket = [[AsyncUdpSocket alloc] initWithDelegate:self];
[udpSocket bindToPort:udpPort error:nil];
[udpSocket enableBroadcast:YES error:nil]; 
NSError *error = nil;
if ([udpSocket connectToHost:bchost onPort:udpPort error:&error])
{
[udpSocket receiveWithTimeout:10 tag:0];
[self sendToUDPServer:@"HELLO"];
}

So, the problem is that it works with "host" but not with "bchost". On both cases I see on the server side that the data is received and the answer is sent to the address of the sender (which should be the iOS device) but on the device I do not get the data when I send it to bchost.

Any idea what I am missing ?

Answer

eemceebee picture eemceebee · Oct 7, 2011

Ok, unfortunately all reply's do not work for me but I found the solution, finally ;)

NSString *bcHost = @"255.255.255.255";
NSString *anyHost = @"0.0.0.0";

int UDP_SOCKET_PORT =         6001;
int DISCOVERY_PORT  =       6003;

udpSocket = [[AsyncUdpSocket alloc] initWithDelegate:self];
[udpSocket bindToAddress:anyHost port:DISCOVERY_PORT error:nil];  
[udpSocket enableBroadcast:YES error:nil]; 
[udpSocket receiveWithTimeout:10 tag:0];
[udpSocket sendData:[@"Hello" dataUsingEncoding:NSASCIIStringEncoding] toHost:bcHost port:UDP_SOCKET_PORT withTimeout:-1 tag:0];

If there is an server behind it, it will trigger a response and this will also allow to get the ip from the server for further processing.