Logo  

CS473 - Computer Networks

Displaying exercises/e5/solution/host.c

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <netdb.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

/* host.c:
 *   A program to print the IP address of a host specified on the command
 *   line. ex:
 * > ./host www.indstate.edu
 * Host: www-prod-cms-003.indstate.edu
 * Aliases: 
 *   www.indstate.edu
 * Host type: IPv4
 * Addresses: 
 *   139.102.15.203
 */

/*
 * A working version can be found at ~sbaker/run/473/h4/host
 */
int main(int argc, char *argv[])
{
  // man 3 gethostbyname for information on the hostent structure:
  struct hostent *host;
  char ipbuf[64];
  int i;

  if (argc < 2) {
    fprintf(stderr,"Usage: host <hostname>\n");
    exit(0);
  }
  
  // Use the gethostbyname() system call to lookup the host provided on the
  // first command line argument (argv[1]), assign the result to host.  If
  // host is NULL, print "Host not found: " followed by name of the host and
  // exit with a value of 1:
  if ((host = gethostbyname(argv[1])) == NULL) {
    printf("Host not found: %s\n", argv[1]);
    exit(1);
  }

  // Print the name of the host:
  printf("Host: %s\n", host->h_name);

  // If h_aliases[0] is not null, then print a list of aliases, otherwise don't:
  // (there may be more than one)
  if (host->h_aliases[0] != NULL) {
    printf("Aliases:\n");
    for(i=0; host->h_aliases[i] != NULL; i++) {
      printf("  %s\n", host->h_aliases[i]);
    }
  }
  // Print the host type (IPv4 or IPv6).
  printf("Host type: %s\n", host->h_addrtype == AF_INET? "IPv4" : "IPv6");

  // Print the addresses, there may be more than one: (ex: www.kernel.org)
  // Use the inet_ntop() function to write the ip-address into ipbuf, then print
  // the string found in ipbuf.
  printf("Addresses:\n");
  for(i=0; host->h_addr_list[i] != NULL; i++) {
    inet_ntop(host->h_addrtype, host->h_addr_list[i], ipbuf, sizeof(ipbuf));
    printf("  %s\n", ipbuf);
  }

  return 0;
}