GCDAsyncUDPSocket源地址返回null

时间:2013-01-23 00:40:08

标签: ios objective-c udp gcdasyncsocket

谷歌代码问题镜:https://groups.google.com/forum/#!topic/cocoaasyncsocket/grhjZSMLr3U

这是我正在阅读回复的代码:

- (void)init {
    udpSocket = [[GCDAsyncUdpSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];

    NSError *error = nil;
    if (![udpSocket bindToPort:UDP_PORT error:&error]) { //not connecting to host
        return;
    }
    if (![udpSocket beginReceiving:&error]) {
        return;
    }
}


- (void)udpSocket:(GCDAsyncUdpSocket *)sock
   didReceiveData:(NSData *)data
      fromAddress:(NSData *)address
withFilterContext:(id)filterContext
{
    NSString *msg = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSLog(@"got data from broadcast: %@",msg);

    NSString *src = [[NSString alloc] initWithData:address encoding:NSUTF8StringEncoding];
    NSLog(@"got src from broadcast: %@",src); 
}

这是发送udp bcast的代码:

- (void)send {
    [udpSocket enableBroadcast:YES error:nil];
    [udpSocket sendData:[self pack:@"134.71.146.49"] toHost:UDP_BCAST_ADDR port:UDP_PORT withTimeout:-1 tag:UDP_BROADCAST_SEND];
}

port和bcast addr分别为55555和255.255.255.255。

控制台输出:

got data from broadcast: 134.71.146.49
got src from broadcast: (null)

got data from broadcast: 134.71.146.49
got src from broadcast: (null)

hex:

 data:     <3133342e 37312e31 34362e34 39>
 address:  <1002d903 864793dd 00000000 00000000>

为什么此处的源地址为空?或者为什么不正确?

1 个答案:

答案 0 :(得分:7)

返回给你的地址字段实际上是一个扁平化为NSData对象的sockaddr_in结构。

这是结构:

struct sockaddr_in {
    __uint8_t   sin_len;
    sa_family_t sin_family;
    in_port_t   sin_port;
    struct  in_addr sin_addr;
    char        sin_zero[8];
};

您可以从地址对象的显示中看到第一个字段sin_len是0x10或16个字节。这是sockaddr_in结构的长度。您可以使用它来判断地址对象是指IPv4对象还是IPv6对象。 IPv6对象将使用sockaddr_in6结构并具有更长的长度。

您可以将该NSData对象复制到sockaddr_in结构中,或者只是拉出右偏移(4到7)的字节,以获得看起来更熟悉的4字节源地址。