我正在使用NSNetService类通过 MDNS 发现来解析 IP 地址。我得到两个结果:
看起来像这样的东西:
ae60::x:1cdf:x:212
(其中x是另一个与其他值相似的值)
还有经典的ip地址,比如:10.xx2
第一个结果也是IP地址吗?
这是我用来检索地址的代码:
char addressBuffer[INET6_ADDRSTRLEN];
for (NSData *data in service.addresses)
{
memset(addressBuffer, 0, INET6_ADDRSTRLEN);
typedef union {
struct sockaddr sa;
struct sockaddr_in ipv4;
struct sockaddr_in6 ipv6;
} ip_socket_address;
ip_socket_address *socketAddress = (ip_socket_address *)[data bytes];
if (socketAddress && (socketAddress->sa.sa_family == AF_INET || socketAddress->sa.sa_family == AF_INET6))
{
const char *addressStr = inet_ntop(
socketAddress->sa.sa_family,
(socketAddress->sa.sa_family == AF_INET ? (void *)&(socketAddress->ipv4.sin_addr) : (void *)&(socketAddress->ipv6.sin6_addr)),
addressBuffer,
sizeof(addressBuffer));
int port = ntohs(socketAddress->sa.sa_family == AF_INET ? socketAddress->ipv4.sin_port : socketAddress->ipv6.sin6_port);
if (addressStr && port)
{
NSString * address = [NSString stringWithFormat:@"%s", addressStr];
NSLog(@"Found service at %s:%d", addressStr, port);
}
}
}