#include #include #include #include #include #include "tcpUtilities.h" int makeConnection( char *host, int portNumber ) { struct hostent *hostInfo; struct sockaddr_in sin; int sock; /* Set up socket address */ bzero( (char *)(&sin), sizeof(sin) ); sin.sin_family = AF_INET; sin.sin_port = htons( (u_short)portNumber ); /* Get destination IP address using the host name. */ /* Put address in sin.sin_addr */ if( hostInfo = gethostbyname(host) ) bcopy( hostInfo->h_addr, (char *)(&sin.sin_addr), hostInfo->h_length ); else if( (sin.sin_addr.s_addr = inet_addr(host)) == INADDR_NONE ) bailOut( "can't get TCP host entry\n" ); /* Allocate a socket */ sock = socket( PF_INET, SOCK_STREAM, 0 ); if( sock < 0 ) bailOut( "can't create socket: %s\n", sys_errlist[errno] ); /* Connect the socket to destination address/port */ if( connect( sock, (struct sockaddr *)&sin, sizeof(sin) ) < 0 ) bailOut( "can't connect to %s.%d: %s\n", host, portNumber, sys_errlist[errno] ); /* The connection is good. Return the socket. */ return( sock ); } /* Modified from pp. 117-118, Comer "Internetworking with TCP/IP, VIII" */ int setUpPassiveSocket( int portNumber, int qLength ) { struct sockaddr_in sin; int sock; /* Set up the socket address */ bzero( (char *)(&sin), sizeof(sin) ); sin.sin_family = AF_INET; sin.sin_addr.s_addr = INADDR_ANY; sin.sin_port = (u_short)htons( portNumber ); /* Allocate a socket */ sock = socket( PF_INET, SOCK_STREAM, 0 ); if( sock < 0 ) bailOut( "can't create socket: %s\n", sys_errlist[errno] ); /* Bind the socket and start listening */ if( bind( sock, (struct sockaddr *)(&sin), sizeof(sin) ) < 0 ) bailOut( "can't bind to %d port: %s\n", portNumber, sys_errlist[errno] ); if( listen( sock, qLength ) < 0 ) bailOut( "can't listen on %d port: %s\n", portNumber, sys_errlist[errno] ); /* The socket is ready. Caller may call accept(). */ return( sock ); } int readFromSocket( int sock, char *where, int bytesToRead ) { int n, bytesToGo; bytesToGo = bytesToRead; while( bytesToGo > 0 ) { n = read( sock, where, bytesToGo ); if( n < 0 ) return( n ); /* error: caller should handle it */ if( n == 0 ) /* EOF */ return( bytesToRead - bytesToGo ); bytesToGo = bytesToGo - n; where = where + n; } return( bytesToRead - bytesToGo ); } void getPeerHostName( int sock, char *name ) { struct sockaddr_in peer; struct hostent *hostInfo; int failed; int pSize=sizeof(peer), iSize=sizeof(struct in_addr); failed = getpeername( sock, (struct sockaddr *)&peer, &pSize ); hostInfo = gethostbyaddr( (char *)(&peer.sin_addr), iSize, AF_INET ); if( !failed && hostInfo ) strcpy( name, hostInfo->h_name ); else name[0] = '\0'; } void bailOut( char *format, ... ) { va_list args; va_start( args, format ); _doprnt( format, args, stderr ); va_end( args ); exit(1); }