8

I can use the code below to get the IPv4 DNS address. With the IPv6 DNS address, res_ninit() can not analyse IPv6 address. Like this, iOS - Get device's DNS server address on IPv6 only network, sin_family is always AF_UNSPEC.

Is there any other solutions to get the IPv6 DNS address? Thanks for help.

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

Edit:

I have already solved the problem like below.

+ (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);

}

Community
  • 1
  • 1
sduMonkey
  • 153
  • 1
  • 7
  • 1
    This worked great for me. Thanks for sharing. Of note - the way I implemented, there were memory leaks until I added free(addr_union); + res_ndestroy(res); + free(res); – William Gustafson Feb 17 '20 at 02:11

0 Answers0