/* 
**
** Title:       comfunc.c 
**
** Description: Functions of comunication for WXC2.
**
*/

#include "../include/includes.h"

/*
**  passivesock - allocate & bind a server socket using TCP or UDP
*/

int
passivesock( const char * transport, u_short portbase, int qlen)
{
	struct sockaddr_in    sin;
	int    s, type;

    memset(& sin, 0, sizeof(sin));
    sin.sin_family = AF_INET;
    sin.sin_port = htons(portbase);
    sin.sin_addr.s_addr = INADDR_ANY;
    bzero(&(sin.sin_zero), 8);

    if ( strcmp(transport, "UDP") == 0)
        type = SOCK_DGRAM;
    else
        type = SOCK_STREAM;
    s = socket(AF_INET, type, 0);
    if (s < 0) {
        perror("socket");
        return -3;
    }
    if (bind(s, (struct sockaddr *) & sin, sizeof(sin)) < 0) {
        perror("bind");
        close(s);
        return -4;
    }

    if (type == SOCK_STREAM && listen(s, qlen) < 0) {
        perror("listen");
        close(s);
        return -5;
    }
    return s;
}

/*
**  passiveUDP - create a passive socket for use in a UDP server
*/

int
passiveUDP(u_short portbase)
{
    return (passivesock("UDP", portbase, 0) );
}

const char *
Inet_ntoa(const long addr)
{
	struct sockaddr_in sin;

	sin.sin_addr.s_addr = addr;
	return ((char *) inet_ntoa(sin.sin_addr) );
}


const long
ppsInet_pton(const char *sp)
{
	struct in_addr    i_addr;

	inet_pton(AF_INET, sp, &i_addr);
	return i_addr.s_addr;
}

/*
const long
GetLocalIP(void)
{
	struct  hostent    *hptr;
	char	hostname[40]="\0";
	struct in_addr *inaddr;
 	
	if ((gethostname(hostname, -1)) != 0){
		return -1;
	}
	if ((hptr = gethostbyname(hostname)) == NULL){
		return -1;
	}
	inaddr = (struct in_addr *)(*hptr->h_addr_list);
	return inaddr->s_addr;
}
*/
int
RecvMsg (int sockfd, u_char *buf, int len, 
				int src_ip, int src_port)
{
	struct sockaddr_in  sin;
	int                 nbytes;

	socklen_t size = sizeof(sin);
    	nbytes = recvfrom(sockfd, &buf, 1024, 
    		0, (struct sockaddr *) &sin, &size);
	src_ip = sin.sin_addr.s_addr;
	src_port = sin.sin_port;
	len = nbytes;
	return nbytes;
}

int
SendMsg (int sockfd, u_char *buf, int len, 
				int dest_ip, int dest_port)
{
	struct sockaddr_in  sin;
	int                 retval=0;    

    bzero(&sin.sin_zero, sizeof(sin.sin_zero));
    sin.sin_family = AF_INET;
	sin.sin_addr.s_addr = dest_ip;
	sin.sin_port = htons(dest_port);
    retval = sendto(sockfd, &buf, len, 0, 
					(struct sockaddr *)&sin, sizeof(sin));
	return retval;
}
