#include #include #include #include #include "socket.h" extern int errno ; #define QLEN 25 // queue length for incoming TCP connections // get_ssock ( int port_num, char *sock_type ) -- creates a server socket, binds it // port_num, and listens for connections int get_ssock ( int port_num, char *sock_type ) { struct sockaddr_in sin ; int stype ; // socket type int sock ; // socket file descriptor int val ; // temporary value holder if ( strcmp ( sock_type, "udp" ) == 0 ) { stype = SOCK_DGRAM ; } else { stype = SOCK_STREAM ; } // create socket sock = socket ( AF_INET, stype, 0 ) ; if ( sock < 0 ) { fprintf ( stderr, "Can't create socket: %s\n", strerror(errno) ) ; exit(1) ; } memset ( &sin, 0, sizeof(sin) ) ; sin.sin_family = AF_INET ; sin.sin_addr.s_addr = INADDR_ANY ; sin.sin_port = htons ( (short) port_num ) ; // try to bind to port_num val = bind ( sock, (struct sockaddr *)&sin, sizeof(sin) ) ; if ( val < 0 ) { fprintf ( stderr, "Can't bind socket: %s\n", strerror(errno) ) ; exit(1) ; } // try to listen if it is a tcp socket if ( stype == SOCK_STREAM ) { val = listen ( sock, QLEN ) ; if ( val < 0 ) { fprintf ( stderr, "Can't listen on socket: %s\n", strerror(errno) ) ; exit(1) ; } } return sock ; } /* get_csock ( const char *host, int port_num, char *sock_type ) -- creates * a client (active) socket, and tries to connect to port_num port of host. * sock_type specifies the socket type to be used, currently accepted * options are "tcp" and "upd". */ int get_csock ( const char *host, int port_num, char *sock_type ) { struct sockaddr_in sin ; struct hostent *hen ; int sock, stype, rval ; if ( strcmp ( sock_type, "udp" ) == 0 ) { stype = SOCK_DGRAM ; } else { stype = SOCK_STREAM ; } sock = socket ( AF_INET, stype, 0 ) ; if ( sock < 0 ) { return -1; } memset ( &sin, 0, sizeof(sin) ) ; sin.sin_family = AF_INET ; sin.sin_port = htons ( (short) port_num ) ; if ( (hen = gethostbyname(host)) ) { // first try alpha-numerical address memcpy ( &sin.sin_addr, hen->h_addr, hen->h_length ) ; } else { // doesn't seem to be alpha-numerical, try dotted decimal if ( inet_pton ( AF_INET, host, &sin.sin_addr ) < 1 ) { return -1; } } rval = connect ( sock, (struct sockaddr *) &sin, sizeof(sin) ) ; if ( rval < 0 ) { return -1; } return sock ; }