ReferencesTopIPv6 APIName to address resolution

Name to address resolution

There is a variety of ways that you can do some translations of hostname to IP address. We have used getaddrinfo function here because currently it seems to be the one that will be here going forward.

A simple program that takes a hostname and returns the addresses for that name is shown below. This is an example of the output:

Orignal host: www.6bone.net
IPv6 address: 3ffe:b00:c18:1::10
IPv4 address: 131.243.129.43

#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>

int main(int argc, char *argv[])
{
  char myname[] = "www.6bone.net";
  char myservice[] = "http";
  char myaddrbuf[NI_MAXHOST];
  struct addrinfo *res;

  if (getaddrinfo(myname, myservice,NULL, &res) == 0) {
    printf("Orignal host: %s\n", myname);
    while (res != NULL) {
       switch(res->ai_family) {
         case AF_INET:
           printf("IPv4 address: ");
           break;
         case AF_INET6:
           printf("IPv6 address: ");
           break;
         default:
           printf("Unknown type %d address: ", res->ai_family);
       }
       if (getnameinfo(res->ai_addr, res->ai_addrlen, myaddrbuf, NI_MAXHOST,NULL, 0,NI_NUMERICHOST) != 0) {
         printf("error with getnameinfo\n");
       } else {
         printf("%s\n", myaddrbuf);
       }

       res = res->ai_next;
    }
  }
  return 0;
}

Notice how we have had to use a while loop for the addresses, then test to see if the address is an IPv4 or IPv6 address. A lot of the time if you use address family independent coding you will not need to do that test. You can see that it is not needed to get the IP address in a printable format. The while loop is used to traverse the linked list.

The flag NI_NUMERICHOST used for the getnameinfo function tells the function to return a string representation of the address. Without this flag the function returns the reverse DNS lookup of the IP address which, if the 6bone.net hostmaster is doing his job, will be www.6bone.net


ReferencesTopIPv6 APIName to address resolution