Search code examples
ioscswiftdnsreal-ip

Is there a way to make separate DNS requests for IPv4 and IPv6 in swift or ObjC


What I have so far is:

void startQueryIPv4(const char *hostName){
printf("startQueryIPv4");
DNSServiceRef serviceRef;
DNSServiceGetAddrInfo(&serviceRef, kDNSServiceFlagsForceMulticast, 0, kDNSServiceProtocol_IPv4, hostName, queryIPv4Callback, NULL);
DNSServiceProcessResult(serviceRef);
DNSServiceRefDeallocate(serviceRef);
}


static void queryIPv4Callback(DNSServiceRef sdRef, DNSServiceFlags flags, uint32_t interfaceIndex, DNSServiceErrorType errorCode, const char *hostname, const struct sockaddr *address, uint32_t ttl, void *context){
printf("queryIPv4Callback");

if (errorCode == kDNSServiceErr_NoError) {

    printf("no error");
    char *theAddress = NULL;

    switch(address->sa_family) {
        case AF_INET: {
            struct sockaddr_in *addr_in = (struct sockaddr_in *)address;
            theAddress = malloc(INET_ADDRSTRLEN);
            inet_ntop(AF_INET, &(addr_in->sin_addr), theAddress, INET_ADDRSTRLEN);
            break;
        }
        case AF_INET6: {
            struct sockaddr_in6 *addr_in6 = (struct sockaddr_in6 *)address;
            theAddress = malloc(INET6_ADDRSTRLEN);
            inet_ntop(AF_INET6, &(addr_in6->sin6_addr), theAddress, INET6_ADDRSTRLEN);
            break;
        }
        default:
            break;
    }
    printf("IP address: %s\n", theAddress);
    free(theAddress);

} else {
    printf("%d", errorCode);
}

}

But the callback is never called. In the console I get this error: TIC Read Status [9:0x0]: 1:57 ObjectiveC is not my power but I had to mess with it. Any help will be appreciated.


Solution

  • Inasmuch as Objective-C is a true superset of C and Darwin is certified compatible with SUS 3, your Objective-C program for iOS should be able to use the C interface to the system's name resolver: getaddrinfo(). You can use the third argument to this function to specify that you want only IPv4 results (or only IPv6 results).

    Things of which you should be aware:

    • this is of course a synchronous interface; if you want asynchronous then you'll need to arrange for that yourself.

    • getaddrinfo() allocates and returns a linked list of addresses, so

      • in principle, you might need to check more than one

      • you need to free the list after you're done with it via freeaddrinfo()