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

#define MAXLEN 100

/*
 * Name resolution through getaddrinfo() calls.
 */
int main(int argc,char *argv[]) {
  int i;

  if (argc<2) {
    fprintf(stderr,"usage: %s name [name...]\n",argv[0]); 
    exit(EXIT_FAILURE);
  }
  for (i=1; i<argc; i++) { // foreach arg
    struct addrinfo *first_info;
    printf("--------%s\n",argv[i]); // which is current arg ?
    if (getaddrinfo(argv[i],NULL,NULL,&first_info)) {
      printf("unknown\n"); // wrong
    } else {
      struct addrinfo *info;
      for (info=first_info; info!=NULL; info=info->ai_next) { // parses every info
	char string[MAXLEN];
	struct sockaddr *saddr = info->ai_addr;
        if (info->ai_socktype==SOCK_DGRAM) continue; // ignore UDP
	switch (saddr->sa_family) {
	case AF_INET: // IPv4
	  {
	    struct sockaddr_in *sin = (struct sockaddr_in *)saddr;
	    inet_ntop(saddr->sa_family,&(sin->sin_addr),string,MAXLEN);
	  }
	  break;
	case AF_INET6: // IPv6
	  {
	    struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)saddr;
	    inet_ntop(saddr->sa_family,&(sin6->sin6_addr),string,MAXLEN);
	  }
	  break;
	default: // What?
	  strcpy(string,"???");
	  break;
	}
	printf("Address: %s\n",string);
      }
      freeaddrinfo(first_info); // I wanna be free...
    }
  }
}