/*
 * Copyright (C) 2004  Roy Keene
 *
 * 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.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 *
 *      email: mrtg@rkeene.org
 */


/*
 *	Network related functions
 */
#include "compat.h"
#include "net.h"

/* This must be the first thing called from `main' */
int net_init(void) {
#ifdef _USE_WIN32_  
	WSADATA wsaData;

	if (WSAStartup(MAKEWORD(2, 0), &wsaData)!=0) {
		return(-1);                           
	}
	if (wsaData.wVersion!=MAKEWORD(2, 0)) {
		/* Cleanup Winsock stuff */    
		WSACleanup();              
		return(-1);  
	}
#endif
	return(0);
}

/*
 *	Create a listening port on tcp port PORT
 */
int net_listen(int port) {
	struct sockaddr_in localname;
	int sockFd;

	sockFd=socket(PF_INET, SOCK_STREAM, IPPROTO_IP);
	localname.sin_family=AF_INET;
	localname.sin_port=htons(port);
	localname.sin_addr.s_addr=INADDR_ANY;
	if (bind(sockFd, (struct sockaddr *) &localname, sizeof(localname))==-1) {
		perror("bind");
		return(-1);
	}
	if (listen(sockFd,1024)==-1) {
		perror("listen");
		return(-1);
	}
	return(sockFd);
}

int net_connect_tcp(char *host, int port) {
	int sockid;
	struct hostent *hostinfo;
	struct sockaddr_in sock;

#ifdef HAVE_INET_ATON
	if (!inet_aton(host,&sock.sin_addr)) {
#else
#ifdef HAVE_INET_ADDR
	if ( (sock.sin_addr.s_addr=inet_addr(host) )==-1) {
#else
	{
#endif
#endif
		if ((hostinfo=gethostbyname(host))==NULL) return(-1);
		memcpy(&sock.sin_addr.s_addr,hostinfo->h_addr_list[0],hostinfo->h_length);
	}

	sock.sin_family=AF_INET;
	sock.sin_port=htons(port);
	if ((sockid=socket(PF_INET, SOCK_STREAM, IPPROTO_IP))<0) {
		return(-1);
	}
	if (connect(sockid, (struct sockaddr *) &sock, sizeof(sock))<0) {
		close(sockid);
		return(-1);
	}
	return(sockid);
}
