
/* 
 * sulahp.c     -gethostbyname with timeout
 * distributed as part of _ s u l a _
 * 
 * Author: Tano Fotang, Feb 1998
 * fotang@techie.com
 * 
 * 
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the Free 
 * Software Foundation; either version 2 of the License , or (at your option) 
 * any later version.
 * see the file COPYING for further information.
 * 
 */


#include <netdb.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <signal.h>
#include <setjmp.h>
#include <stdlib.h>
#include <stdio.h>
#ifndef INADDR_NONE
#define INADDR_NONE     0xffffffff
#endif

static jmp_buf env;
static void sig_alrm(int signo)
{
	longjmp(env, 1);
}
void    main(int argc, char **argv)
{
	int     n;
	char   *server = 0;
	unsigned timeout = 0;
	while ((n = getopt(argc, argv, "s:t:")) != EOF){
		switch (n) {
		    case 's':
			    server = optarg;
			    break;
		    case 't':
			    timeout = atoi(optarg);
			    break;
		}
	}
	if (!server)
		exit(-1);
	if (inet_addr(server) != INADDR_NONE)
		printf("%s",server);
	else{
		struct hostent *hp;
		if (timeout) {
			if (signal(SIGALRM, sig_alrm) == SIG_ERR)
				exit(errno);
			if (setjmp(env) != 0)
				exit(-2);
			alarm(timeout);
		}
		hp = gethostbyname(server);
		if (timeout)
			alarm(0);
		if (hp == NULL)
			exit(h_errno);
		printf("%s", inet_ntoa(*((struct in_addr *) *hp->h_addr_list)));
	}
	exit(0);
}
