#include "comm.h"

u_short	portbase = 0;

int	passivesock(char *service, char *protocol, int qlen)
{
	struct servent	*pse;
	struct protoent	*ppe;
	struct sockaddr_in sin;
	int	s, type;

	/*bzero((char *)&sin, sizeof(sin));*/
	memset((char *)&sin, 0, sizeof(sin));
	sin.sin_family = AF_INET;
	sin.sin_addr.s_addr = INADDR_ANY;

	if( pse = getservbyname(service, protocol))
	  sin.sin_port = htons(ntohs((u_short)pse->s_port) + portbase);
	else if((sin.sin_port = htons((u_short)atoi(service))) == 0)
	{ printf("Can't get \"%s\" service entry\n",service);
	  return(-1);}

	if((ppe = getprotobyname(protocol)) == 0)
	{ printf("Cant get \"%s\" protocol entry\n",protocol);
	  return(-1);}

	if(strcmp(protocol, "udp") == 0)
	  type = SOCK_DGRAM;
	else
	  type = SOCK_STREAM;

	s = socket(PF_INET, type, ppe->p_proto);
	if (s < 0)
	{ printf("Can't create socket: %s\n",sys_errlist[errno]);
	  return(-1);}

	if(bind(s, (struct sockaddr *)&sin, sizeof(sin)) < 0)
	{ printf("Can't bind to %s port: %s\n",service,sys_errlist[errno]);
	  return(-1);}

	if(type == SOCK_STREAM && listen(s,qlen) < 0)
	{ printf("Can't listen on %s port: %s\n",service,sys_errlist[errno]);
	  return(-1);}

	return(s);
}

int	passiveUDP(char *service)
{

	return passivesock(service,"udp",0);
}

int	passiveTCP(char *service, int qlen)
{

	return passivesock(service,"tcp",qlen);
}

int	connectsock(char *host, char *service, char *protocol)
{
struct	hostent	*phe;
struct	servent	*pse;
struct	protoent *ppe;
struct	sockaddr_in sin;
int	s, type;

	/*bzero((char *)&sin, sizeof(sin));*/
	memset((char *)&sin, 0, sizeof(sin));
	sin.sin_family = AF_INET;

	if(pse = getservbyname(service, protocol))
	  sin.sin_port = pse->s_port;
	else if((sin.sin_port = htons((u_short)atoi(service))) == 0)
	{ printf("Can't get \"%s\" service entry\n",service);
	  return(-1);}

	if(phe = gethostbyname(host))
	  memcpy((char *)&sin.sin_addr, phe->h_addr, phe->h_length);
	else if((sin.sin_addr.s_addr = inet_addr(host)) == INADDR_NONE)
	{ printf("Can't get \"%s\" host entry\n",host);
	  return(-1);}

	if((ppe=getprotobyname(protocol)) == 0)
	{ printf("Can't get \"%s\" protocol entry\n", protocol);
	  return(-1);}

	if(strcmp(protocol, "udp") == 0)
	  type = SOCK_DGRAM;
	else
	  type = SOCK_STREAM;

	s = socket(PF_INET, type, ppe->p_proto);
	if(s < 0)
	{ printf("Can't create socket: %s\n",sys_errlist[errno]);
	  return(-1);}

	if(connect(s, (struct sockaddr *)&sin, sizeof(sin)) < 0)
	{ printf("Can't connect to %s.%s: %s\n",host,service,
	          sys_errlist[errno]);
	  return(-1);}

	return s;
}

int	connectUDP(char *host, char *service)
{

	return connectsock(host, service, "udp");
}

int	connectTCP(char *host, char *service)
{

	return connectsock(host, service, "tcp");
}

