Horhe Garcia
Horhe Garcia

Reputation: 902

sending UDP request to 255.255.255.255 and waiting for reply in iOS

Im would to send a UDP broadcast from an iPhone, and then listen for a UDP response with a timeout period from all devices with such port opened. Does my custom device from the same subnet would answer? ( if mine is 192.168.1.100 and IP of custom device is 192.168.1.201 ) What to use "SmallSockets" or "cocoaAsyncSocket" ? What function to use to listen for response? Thanx!

Upvotes: 1

Views: 1972

Answers (1)

Horhe Garcia
Horhe Garcia

Reputation: 902

i decided to use cocoaAsyncSocket. To broadcast you can use:

[udpSocket sendData:datatosend toHost:@"192.168.1.113" port:port withTimeout:-1 tag:0];

to receive:

- (void)udpSocket:(GCDAsyncUdpSocket *)sock didReceiveData:(NSData *)data fromAddress:(NSData *)address withFilterContext:(id)filterContext
{
    NSString *msg = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease];

    NSString *host = nil;
    uint16_t port = 0;
    [GCDAsyncUdpSocket getHost:&host port:&port fromAddress:address];

    if (msg)
    {   
        NSLog(@"Message = %@, Adress = %@ %i",msg,host,port);
    }
    else
    {
        NSLog(@"Error converting received data into UTF-8 String");
    }
}

Upvotes: 3

Related Questions