# include <stdio.h>
# include <signal.h>
# include <ctype.h>
# include <sys/types.h>
# include <sys/socket.h>
# include <netinet/in.h>
# include <netdb.h>
# include <errno.h>
# include <sys/param.h>
# include <malloc.h>

#ifdef STANDALONE
main(argc, argv)
	int argc;
	char * argv[];
{
	char *port = argv[1] , *host=argv[2];

	TestPORT( port, host );
}
#endif

TestPORT( port, host )
char *port,*host;
{                                               
	register struct hostent *hp;
	int s;
	struct sockaddr_in i;
	/* assume tcp */
	register struct servent *sp = getservbyname(port, "tcp");
	int verbose = 0;
	int status = 0;

	/* Name or number? */
                        
	i.sin_addr.s_addr = inet_addr(host);
	hp = gethostbyaddr((char *)&i.sin_addr.s_addr, 4, AF_INET);
	if (hp == NULL)
	{
		fprintf(stderr, "Warning:  Can't do reverse query on %s\n", host);
		if (errno)
			perror("gethostbyaddr");
		/*
		 * stuff my own hostent together ...
		 */
		 hp = (struct hostent *)malloc(sizeof(*hp));
		 hp->h_name = malloc(strlen("unknown")+1);
		 strcpy(hp->h_name, "unknown");
		 hp->h_aliases = 0;
		 hp->h_addrtype = AF_INET;
		 hp->h_length = 4;
		 hp->h_addr_list = (char **)malloc(2*(sizeof(char **)));
		 hp->h_addr_list[0] = malloc(sizeof (char *));
		 *(int *)hp->h_addr_list[0] = inet_addr(host);
		 hp->h_addr_list[1] = 0;
	}
	i.sin_family = AF_INET;

	if (sp == NULL)
	{
		fprintf(stderr, " unknown service %s\n", port);
#ifdef STANDALONE
		exit(1);
#else
		return(0);
#endif
	}
	i.sin_port = sp->s_port;
	

	/* try and connect */
	s = socket(AF_INET, SOCK_STREAM, 0);
	if (s < 0)
	{
		perror("socket");
#ifdef STANDALONE
		exit(2);
#else
		return(0);
#endif
	}

	if (hp != NULL)
		bcopy(*hp->h_addr_list, &i.sin_addr, hp->h_length);
	if (verbose)
		fprintf(stdout, "connecting to host %s (%s), port %d (%s)\n",
			inet_ntoa(i.sin_addr.s_addr), hp ? hp->h_name : "unknown", 
			 ntohl(i.sin_port), getservbyport(i.sin_port, "tcp")->s_name);

	if (connect(s, &i, sizeof (i)) < 0)
	{
		perror("connect");
		close(s);
#ifdef STANDALONE
		exit(3);
#else
		return(0);
#endif
	}
	else
	{
		if (verbose)
			fprintf(stdout,"connect OK\n");
		close(s);
	}
#ifdef STANDALONE
	exit(0);
#else
	return(1);
#endif
}
