我可以使用以下代码获取IPv4 DNS地址。使用IPv6 DNS地址,res_ninit()
无法分析IPv6地址。像这样,iOS - Get device's DNS server address on IPv6 only network,sin_family
始终为AF_UNSPEC
。
是否有其他解决方案可以获取IPv6 DNS地址?谢谢你的帮助。
+ (void)outPutDNSServers {
res_state res = malloc(sizeof(struct __res_state));
int result = res_ninit(res);
if ( result == 0 ) {
for ( int i = 0; i < res->nscount; i++ ) {
NSString *s = [NSString stringWithUTF8String : inet_ntoa(res->nsaddr_list[i].sin_addr)];
NSLog(@"%@",s);
}
}
else {
NSLog(@"%@",@" res_init result != 0");
}
res_nclose(res);
}
编辑:
我已经解决了下面的问题。
+ (void)outPutDNSServers {
res_state res = malloc(sizeof(struct __res_state));
int result = res_ninit(res);
if (result == 0) {
union res_9_sockaddr_union *addr_union = malloc(res->nscount * sizeof(union res_9_sockaddr_union));
res_getservers(res, addr_union, res->nscount);
for (int i = 0; i < res->nscount; i++) {
if (addr_union[i].sin.sin_family == AF_INET) {
char ip[INET_ADDRSTRLEN];
inet_ntop(AF_INET, &(addr_union[i].sin.sin_addr), ip, INET_ADDRSTRLEN);
NSString *dnsIP = [NSString stringWithUTF8String:ip];
NSLog(@"IPv4 DNS IP: %@", dnsIP);
} else if (addr_union[i].sin6.sin6_family == AF_INET6) {
char ip[INET6_ADDRSTRLEN];
inet_ntop(AF_INET6, &(addr_union[i].sin6.sin6_addr), ip, INET6_ADDRSTRLEN);
NSString *dnsIP = [NSString stringWithUTF8String:ip];
NSLog(@"IPv6 DNS IP: %@", dnsIP);
} else {
NSLog(@"Undefined family.");
}
}
}
res_nclose(res);
}