/*Andrea James CS35010 Assignment 26 March 1998 drinks client All socket code based on lecture notes */ #include #include #include #include #include #include #include #include #include #include /*A function to create a client socket that can connect to *a server*/ int call_socket (char *host, int port); /*Converts characters representing a 4-digit number into an *equivalent integer. Used for interpreting messages from the *server*/ int ConvertCharToInt (char *the_string); void main () { int s; /*variable for socket*/ int port; /*holds port number*/ struct servent *the_servent; char user[5], servername[20]; char buffer[40]; int x, size; /*get port number of created service (aaj8) */ the_servent = getservbyname ("aaj8", "tcp"); if ( the_servent == NULL ) {printf ("Error getting port number.\n"); exit (1);} port = the_servent->s_port; printf ("Port number is %d.\n", port); /*request for a server name*/ printf ("Please enter a server name: "); scanf ("%s", servername); /*pass & retrieve information over connection*/ printf ("Control-C to exit.\n\n"); /*infinite loop*/ while (1) { /*prompt user for a message to pass to server*/ printf ("prompt>"); scanf ("%s", user); /*use call_socket function to connect to specified server*/ if ( (s=call_socket (servername, port)) < 0 ) {perror("Call Failed."); exit(1);} printf ("Data socket is %d\n", s); /*write message to server*/ x=write (s, user, 5); /*read response*/ x=read (s, buffer, 4); size=ConvertCharToInt(buffer); x=read (s, buffer, size); /*output response to the screen*/ buffer[size-1]='\0'; printf ("\nServer reply:\n%s\n", buffer); /*close connection*/ close(s); } } int call_socket (char *host, int port) { struct sockaddr_in sa; struct hostent *hp; int s; if ( (hp=gethostbyname(host)) == NULL ) {errno=ECONNREFUSED; return (-1);} memset ( &sa, 0, sizeof(sa) ); memcpy( (char*)&sa.sin_addr, hp->h_addr, hp->h_length ); sa.sin_family = hp->h_addrtype; sa.sin_port = htons( (u_short)port ); if ( (s = socket(hp->h_addrtype, SOCK_STREAM, 0)) < 0 ) return (-1); if ( connect(s, (struct sockaddr*)&sa, sizeof(sa)) < 0 ) return (-1); return (s); } int ConvertCharToInt (char *the_string) { int temp=0; temp = ( ((int)the_string[0]) - 48)*1000; temp += ( ((int)the_string[1]) - 48)*100; temp += ( ((int)the_string[2]) - 48)*10; temp += ( ((int)the_string[3]) - 48); return temp; }