/* File:    my-nslookup.c
 * Author:  Janet Davis
 * Created: November 4, 2006
 * Revised: June 26, 2008
 * Purpose: Illustrates the use of getaddrinfo(...) to get a sockaddr_in
 *          structure for a given hostname.
 */
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <netinet/in.h>
#include <arpa/inet.h>

int main(int argc, char* argv[]) {
  struct addrinfo* res;
  char* hostname;
  char* hostaddr;
  struct sockaddr_in* saddr;
  
  if (argc != 2) {
    perror("Usage: hostnamelookup <hostname>\n");
    exit(1);
  }

  hostname = argv[1];

  /* Resolve the hostname to an addrinfo structure */
  if (0 != getaddrinfo(hostname, NULL, NULL, &res)) {
    fprintf(stderr, "Error in resolving hostname %s\n", hostname);
    exit(1);
  }

  /* Extract the sockaddr and cast to sockaddr_in */
  saddr = (struct sockaddr_in*)res->ai_addr;

  /* Convert the address to numbers-and-dots notation (a char * string)
   * (This is only necessary if a human being will read the address.)
   * Note that the string returned comes from a static memory area.
   */
  hostaddr = inet_ntoa(saddr->sin_addr);

  printf("Address for %s is %s\n", hostname, hostaddr);
  exit(0);
}
