#include /* standard C i/o facilities */ #include /* needed for atoi() */ #include /* Unix System Calls */ #include /* system data type definitions */ #include /* socket specific definitions */ #include /* INET constants and stuff */ #include /* IP address conversion stuff */ #include /* Name lookups (gethostbyname) */ #include "wrappers.h" /* Simple TCP client that expects a hostname and port number on the command line. Connects and sends a message. */ /* define the message we will send */ char *message = "Networking Rules !!!\n"; /* client program: The following must passed in on the command line: name of the server (argv[1]) port number of the server (argv[2]) */ int main( int argc, char **argv ) { int sk; struct sockaddr_in skaddr; struct hostent *hp; /* used for name lookup */ /* first - check to make sure there are 2 command line parameters (argc=3 since the program name is argv[0]) */ if (argc!=3) { printf("Usage: client \n"); exit(0); } /* create a socket - use wrapper function! IP protocol family (PF_INET) TCP protocol (SOCK_STREAM) */ sk = np_socket( PF_INET, SOCK_STREAM, 0 ); /* fill in an address structure that will be used to specify the address of the server we want to connect to address family is IP (AF_INET) server IP address is found by calling gethostbyname with the name of the server (entered on the command line) server port number is argv[2] (entered on the command line) */ skaddr.sin_family = AF_INET; /* convert argv[1] to a network byte order binary IP address */ /* First try to convert using gethostbyname */ if ((hp = gethostbyname(argv[1]))!=0) { /* Name lookup was successful - copy the IP address */ memcpy( &skaddr.sin_addr.s_addr, hp->h_addr, hp->h_length); } else { /* Name lookup didn't work, try converting from dotted decimal */ #ifndef SUN if (inet_aton(argv[1],&skaddr.sin_addr)==0) { printf("Invalid IP address: %s\n",argv[1]); exit(1); } #else /*inet_aton is missing on Solaris - you need to use inet_addr! */ /* inet_addr is not as nice, the return value is -1 if it fails (so we need to assume that is not the right address !) */ skaddr.sin_addr.s_addr = inet_addr(argv[1]); if (skaddr.sin_addr.s_addr ==-1) { printf("Invalid IP address: %s\n",argv[1]); exit(1); } #endif } skaddr.sin_port = htons(atoi(argv[2])); /* attempt to establish a connection with the server */ np_connect(sk,(struct sockaddr *) &skaddr,sizeof(skaddr)); /* Send a string and finish*/ if (write(sk,message,strlen(message))<0) { printf("write() returned an error!\n"); } close(sk); return(0); }