/* NAME : client.C TYPE : C++ SOURCE AUTHOR : Arunkumar Elango DESCRIPTION : This file contains the source code for the client. It takes the following command line as input : $ client [-h hostname] [-p portnumber] The client tries to connect to the server at the known portnumber and host. If it succeds in connecting, it takes a string as input from the user. It then sends this string to the server, through the socket, and then reads the server's response from the socket. It prints this reponse to the screen and quits. */ #include #include #include #include #include #include #include #include #include const int MAXSTR=1024; const long PORTNUM=54715; main( int argc, char *argv[]) { int portNumber; char hostName[MAXSTR]; if ( (argc != 5) && (argc != 3) && (argc != 1) ) { cerr << "Invalid command line.\n"; exit(1); } if ( argc == 1 ) { strcpy(hostName,"ernie.eecs.uic.edu"); portNumber = PORTNUM; } else if (argc == 3 ) { if (!strcmp(argv[1],"-h")) { strcpy(hostName,argv[2]); portNumber = PORTNUM; } else if (!strcmp(argv[1],"-p")) { portNumber = atoi(argv[2]); strcpy(hostName,"ernie.eecs.uic.edu"); } else { cerr << "Invalid command line.\n"; exit(1); } } else { if ((!strcmp(argv[1],"-h")) && (!strcmp(argv[3],"-p"))) { strcpy(hostName,argv[2]); portNumber = atoi(argv[4]); } else { cerr << "Invalid command line.\n"; exit(1); } } if (portNumber < 10000) { cerr << "Port number has to be atleast 10000.\n"; exit(1); } cout << "host = " << hostName << " port = " << portNumber << endl; struct hostent *hostptr; if ((hostptr = gethostbyname(hostName)) == NULL) { cerr <<"Error locating host : "<h_addr,hostptr->h_length); serv_addr.sin_port = htons(portNumber); int sockfd,newsockfd; if ((sockfd = socket(AF_INET,SOCK_STREAM,0)) < 0) { cerr << "client : socket error.\n"; exit(1); } if ( connect(sockfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr)) < 0) { cerr << "client : connect error.\n"; exit(1); } char data[MAXSTR]; char answer[MAXSTR]; cout << "String to send to the server : "; cin.getline(data,MAXSTR,'\n'); data[strlen(data)] = '\0'; write(sockfd,data,strlen(data)); read(sockfd,(void *)answer,MAXSTR); cerr << answer <