/*	Project Group : Muhammad Rashid Mahfooz, Salman Zubair, Syed Shahzad Ali
 *			CS742 COMPUTER COMMUNICATION NETWORKS
 *			Wichita State University
 *			Wichita Kansas
 *
 *	Created:	September 18, 2001
 *
 *	Program: 	This program provides the user a facility to get 
 * 		 	the ip address(s) and host names of any internet
 * 		 	host
 *
 *	Modified:	September 19, 2001
 */

/* Included Header Files */
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<netinet/in.h>
#include<sys/socket.h>
#include<netdb.h>
#include <arpa/inet.h>


/* Function Prototypes */
int getHostIPs(char *host_name);
int getHostName(char *host_ip);


/* Mian Function */
int main(int argc, char *argv[])
{
int status=0;	/* switch variable */ 

/**
 * error checking block
 */
if(argc<2 || argc >3)
{
	printf("Usage : gethost <domain name>\n");
	printf("or\n");
	printf("Usage : gethost [-r] <ip address>\n");
	exit(1);
}

if(argc==2)
	status=1;
if(argc==3)
	{
		if(strcmp(argv[1], "-r") != 0)
		{
			printf("Usage : gethost <domain name>\n");
			printf("or\n");
			printf("Usage : gethost [-r] <ip address>\n");
			exit(1);
		}
	status=2;
	}


switch(status)
	{
	case 1:
		if( getHostIPs(argv[1]) == -1)
			exit(1);
		break;

	case 2:
                if( getHostName(argv[2]) == -1)
			exit(1);
		break;
	
	default:
		break;

	}
return EXIT_SUCCESS;
}



/**
 * getHostIPs():This function prints all the IP addresses of  
 * 		the given host 
 *
 * inputs:	host name provided by command line argument
 *
 * returns:	-1 on error 0 on ok
 */
int getHostIPs(char *host_name)
{

int i=0;	/* loop variable */
struct hostent *hp;
struct in_addr *ip_addr;

	if( (hp = gethostbyname(host_name)) == NULL )
	{
		printf("Invalid Input\n");
		printf("Program Exiting....\n");
		return -1;
	}
	if(hp->h_addrtype == AF_INET)
	{
		printf("Hostname: %s \n", host_name);
		while( hp->h_addr_list[i] )
		{
			ip_addr = (struct in_addr*)hp->h_addr_list[i];
			printf("IP Address: %s\n",inet_ntoa(*ip_addr));
			i++;	 
		}
	}
	return 0;
}


/**
 * getHostName:	This function prints the name of the host
 * 		corresponding to the given ip address.  
 *
 * inputs:	Host ip address 
 *
 * returns:     -1 on error, 0 on ok
 */
int getHostName(char *host_ip)
{
struct hostent *hp;
struct in_addr ip_addr;

	if( inet_aton(host_ip, &ip_addr) == 0 )
	{
		printf("Inavlid Input\n");
		printf("Program Exiting....\n");
		return -1;
	}
	if( (hp = gethostbyaddr( (char*) (&ip_addr), sizeof(struct in_addr), AF_INET)) == NULL)
	{
		printf("Host not found\n");
		printf("Program Exiting....\n");
		return -1;	
	}
	printf("hostname : %s\n", hp->h_name);
	return 0;
}
