您可以将CFDataRef转换为NSData,而不是将BYTES分配给结构sockaddr。
如果地址可能是 IP6 或 IP4,请检查 INET FAMILY,然后将BYTES分配给正确的结构(sockaddr_in用于 IP4 或sockaddr_in6用于 IP6)
例如,假设地址是CFDataRef 地址类型的值
NSString *addressString;
int port=0;
struct sockaddr *addressGeneric;
struct sockaddr_in addressClient;
NSData *myData = (__bridge NSData *)address;
addressGeneric = (struct sockaddr *) [myData bytes];
switch( addressGeneric->sa_family ) {
case AF_INET: {
struct sockaddr_in *ip4;
char dest[INET_ADDRSTRLEN];
ip4 = (struct sockaddr_in *) [myData bytes];
port = ntohs(ip4->sin_port);
addressString = [NSString stringWithFormat: @"IP4: %s Port: %d", inet_ntop(AF_INET, &ip4->sin_addr, dest, sizeof dest),port];
}
break;
case AF_INET6: {
struct sockaddr_in6 *ip6;
char dest[INET6_ADDRSTRLEN];
ip6 = (struct sockaddr_in6 *) [myData bytes];
port = ntohs(ip6->sin6_port);
addressString = [NSString stringWithFormat: @"IP6: %s Port: %d", inet_ntop(AF_INET6, &ip6->sin6_addr, dest, sizeof dest),port];
}
break;
default:
addressString=@"Error on get family type.";
break;
}
NSLog(@"Client Address: %@",addressString);
这是输出
2013-08-25 12:22:35.308 FGWakeService[9283:303]客户端地址:IP4:192.168.69.38 端口:58614