/*
 *  lib/net.c
 *
 *  Network utilities
 *
 *  Copyright (C) 2004  Phoenix Grid Computing Project
 *                      ( http://www.logos.ic.i.u-tokyo.ac.jp/phoenix/ )
 *
 *  2004-11-26  Implemented basic functions 
 *              by Kaneda Kenji
 */


#include "common.h"
#include "debug.h"
#include "std.h"
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <netdb.h>


int
Socket ( int domain, int type, int protocol )
{
	int ret;
	
	ret = socket ( domain, type, protocol );
	
	if ( ret == -1 )
		sys_failure ( "socket" );
	
	return ret;
}

void
Bind ( int sockfd, struct sockaddr *my_addr, socklen_t addrlen )
{
	int ret;
	
	assert ( my_addr != NULL );

	ret = bind ( sockfd, my_addr, addrlen );
	
	if ( ret == -1 )
		sys_failure ( "bind" );
}

void
Listen ( int s, int backlog )
{
	char *p;
	int ret;
	int n;
	
	p = getenv("LISTENQ");
	n = ( p != NULL ) ? atoi ( p ) : backlog;
	
	ret = listen ( s, n );
	
	if ( ret == -1 )
		sys_failure ( "listen" );
}

void
Setsockopt ( int s, int level, int optname, const void *optval, socklen_t optlen )
{
	int ret;
	
	ret = setsockopt ( s, level, optname, optval, optlen );
	
	if ( ret == -1 )
		sys_failure ( "setsockopt" );
}

void
Setsockopt_reuseaddr ( int s )
{
	const int on = 1;
	
	Setsockopt ( s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on) );
}

struct hostent *
Gethostbyname ( const char *name )
{
	struct hostent *ret;
	
	assert ( name != NULL );
	
	ret = gethostbyname ( name );
	
	if ( ret == NULL )
		sys_failure ( "gethostbyname" );
	
	return ret;
}

in_addr_t 
in_addr_of_hostname ( const char *name )
{
	struct hostent *hp;    
	
	assert ( name != NULL );
	
	hp = Gethostbyname ( name );
	
	return *( in_addr_t * )hp->h_addr_list[0];
}

struct sockaddr_in
create_inet_sockaddr ( in_addr_t in_addr, int port )
{
	struct sockaddr_in  x;
	
	mzero ( &x, sizeof ( x ) );
	
	x.sin_family = AF_INET;
	x.sin_addr.s_addr = in_addr;
	x.sin_port = htons ( port );
	
	return x;
}
