get ip address by DNS

目前要解析DNS去解析IP,
但是gethostbyname並不支援IPv6,
但有找到getaddrinfo可以達到同樣的功能,
而且同時有支援IPv4與IPv6

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

int main(int argc, char *argv[])
{
   struct addrinfo hints, *res, *p;
   int status;
   char ipstr[INET6_ADDRSTRLEN];

   if (argc != 2) {
       fprintf(stderr,"usage: showip hostname\n");
       return 1;
   }

   memset(&hints, 0, sizeof hints);
   hints.ai_family = AF_UNSPEC; // AF_INET or AF_INET6 to force version
   hints.ai_socktype = SOCK_STREAM;

   if ((status = getaddrinfo(argv[1], NULL, &hints, &res)) != 0) {
       fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(status));
       return 2;
   }

   printf("IP addresses for %s:\n\n", argv[1]);

   for(p = res;p != NULL; p = p->ai_next) {
       void *addr;
       char *ipver;

       // get the pointer to the address itself,
       // different fields in IPv4 and IPv6:
       if (p->ai_family == AF_INET) { // IPv4
           struct sockaddr_in *ipv4 = (struct sockaddr_in *)p->ai_addr;
           addr = &(ipv4->sin_addr);/*error*/
           ipver = "IPv4";
       } else { // IPv6
           struct sockaddr_in6 *ipv6 = (struct sockaddr_in6 *)p->ai_addr;
           addr = &(ipv6->sin6_addr);/*error*/
           ipver = "IPv6";
       }

       // convert the IP to a string and print it:
       inet_ntop(p->ai_family, addr, ipstr, sizeof ipstr);
       printf("  %s: %s\n", ipver, ipstr);
   }

   freeaddrinfo(res); // free the linked list

   return 0;
}

參考資料:
Sample getaddrinfo Code Compiles in Linux but not FreeBSD
getaddrinfo(3) - Linux man page
gethostbyname(), gethostbyaddr()
Porting IPv4 applications to IPv6
Porting IPv6 -- examples