How to receive Multicast UDP?

2019-04-12 23:13发布

问题:

I'm using GCDAsyncUdpSocket and i can send either Multicast or normal UDP packets. I'm receiving normal packets with no problem but I cant receive Multicast packets from another iOS device.

To receive I use:

- (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");
}
}

回答1:

Make sure the socket is properly set up for multicast. Here's what I'm doing in my multicast project:

- (void)setupSocket
{
    udpSocket = [[GCDAsyncUdpSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
    NSError *error = nil;
    if (![udpSocket bindToPort:5555 error:&error])
    {
        NSLog(@"Error binding to port: %@", error);
        return;
    }
    if(![udpSocket joinMulticastGroup:@"226.1.1.1" error:&error]){
        NSLog(@"Error connecting to multicast group: %@", error);
        return;
    }
    if (![udpSocket beginReceiving:&error])
    {
        NSLog(@"Error receiving: %@", error);
        return;
    }
    NSLog(@"Socket Ready");
}