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

int main(int argc, char *argv[])
{
  struct hostent *h;
  int i;
  char addr[INET6_ADDRSTRLEN + 1];

  /* Check the input. Basic checking only. This is sample code not
     a user utility. */
  if(argc != 2)
  {
    fprintf(stderr, "Usage: gethostbyname <hostname>\n");
    return(1);
  }

  /* Do the query. (Note we will not actually try to resolve IP addresses) */
  if(NULL == (h = gethostbyname(argv[1])))
  {
    fprintf(stderr, "No results from gethostbyname().\n");
    return(1);
  }

  /* Get the hostname. This will be an IP address if we passed an IP address
     to gethostbyname(). */
  printf("Host Name: %s\n", h->h_name);

  /* List all the aliases */
  i = 0;
  while(h->h_aliases[i])
  {
    printf("Alias[%d]: %s\n", i + 1, h->h_aliases[i]);
    i++;
  }

  /* What type of address are we returinig */
  printf("Address Type: ");
  switch(h->h_addrtype)
  {
  case AF_INET:
    printf("AF_INET");
    break;
  case AF_INET6:
    printf("AF_INET6");
    break;
  default:
    printf("UNKNOWN");
    break;
  }
  printf("\n");

  /* What is the length of the address that is returned */
  printf("Address length: %d bytes\n", h->h_length);

  /* Step through the list and print all addresses. */
  i = 0;
  while(h->h_addr_list[i])
  {
    /* The address list is in "binary" format. To print it we need to
       convert the address into a dotted quad (or proper IPv6 representation)
       using inet_ntop() */
    inet_ntop(h->h_addrtype,
	      h->h_addr_list[i],
	      addr,
	      INET6_ADDRSTRLEN + 1);
    
    printf("Address[%d]: %s\n", i + 1, addr);
    i++;
  }

  return(0);
}