/***********************************************************
 * gethost                                                 *
 * a simple DNS resolver                                   *
 * Verteilte Systeme II Kapitel 7                          *
 ***********************************************************
 * 1998 by Frank Kargl (frank.kargl@rz.uni-ulm.de)         *
 ***********************************************************
 * Usage: gethost <ip>|<dns>                               *
 ***********************************************************/

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

/***********************************************************
 *                                                         *
 * Function:                                               *
 * void usage(char* name)                                  *
 * print usage message                                     *
 * Parameters:                                             * 
 *  name - name of executable                              *
 * Return:                                                 *
 *  -                                                      *
 *                                                         *
 ***********************************************************/

void usage(char* name) {
    printf("%s - a simple dnsresolver\n", name);
    printf("Usage: %s <ip>|<dns-name>)\n", name);
    exit(1);
}


int main(int argc, char** argv) {
    
    char address[128];		/* address or as string */
    in_addr_t inaddr;		/* address as structure */
    struct in_addr in;		/* one more structure */
    struct hostent* he;		/* hostentry */

    /* check for arg */
    if (argc == 2) {
	strcpy(address,argv[1]);
    } else {
	usage(argv[0]);
    }
    
    /* check if name or ip supplied */
    /* VERY simple test */
    if (address[0] >= '0' && address[0] <= '9') {
	inaddr = inet_addr(address);
	if (inaddr == (in_addr_t)-1) {
	    printf("no valid ip address\n");
	    exit(0);
	}
	
	/* resolve addr */
	he = gethostbyaddr((char *)&inaddr, sizeof(in_addr_t), AF_INET);
	if (he == NULL) {
	printf("Canīt resolve %s\n", address);
	exit(0);
    }
    
	printf("%s\t%s\n", address, he->h_name);
	exit(0);
    }
    
    /* resolve name */
    he = gethostbyname(address);
    if (he == NULL) {
  	printf("Canīt resolve %s\n", address);
	exit(0);
    }

    memcpy(&in.s_addr, he->h_addr, sizeof (in.s_addr));
    printf("%s\t%s\n", inet_ntoa(in), he->h_name);

    return 0;

}
