/***************************************************************************** *** Demo program explaining the client-server model *** *** This is the client program *** *** Written by Abhijit Das, CSE, IIT Kharagpur *** *** Last modified: October 13, 2006 *** *****************************************************************************/ #include #include #include #include #include #include #include #include /* Global constants */ #define SERVICE_PORT 41041 #define MAX_LEN 1024 #define DEFAULT_SERVER "10.5.17.128" /* Function prototypes */ int serverConnect ( char * ); void serverTalk ( int ); /* Connect with the server: socket() and connect() */ int serverConnect ( char *sip ) { int cfd; struct sockaddr_in saddr; /* address of server */ int status; /* request for a socket descriptor */ cfd = socket(AF_INET, SOCK_STREAM, 0); if (cfd == -1) { fprintf(stderr, "*** Client error: unable to get socket descriptor\n"); exit(1); } /* set server address */ saddr.sin_family = AF_INET; /* Default value for most applications */ saddr.sin_port = htons(SERVICE_PORT); /* Service port in network byte order */ saddr.sin_addr.s_addr = inet_addr(sip); /* Convert server's IP to short int */ bzero(&(saddr.sin_zero),8); /* zero the rest of the structure */ /* set up connection with the server */ status = connect(cfd, (struct sockaddr *)&saddr, sizeof(struct sockaddr)); if (status == -1) { fprintf(stderr, "*** Client error: unable to connect to server\n"); exit(1); } fprintf(stderr, "Connected to server\n"); return cfd; } /* Interaction with the server */ void serverTalk ( int cfd ) { char buffer[MAX_LEN]; int nbytes, status; /* receive greetings from server */ nbytes = recv(cfd, buffer, MAX_LEN-1, 0); if (nbytes == -1) { fprintf(stderr, "*** Client error: unable to receive\n"); return; } buffer[nbytes] = '\0'; printf("%s",buffer); fflush(stdout); /* read string from user */ fgets(buffer, MAX_LEN, stdin); buffer[strlen(buffer)-1] = '\0'; /* send the user's response to the server */ status = send(cfd, buffer, strlen(buffer), 0); if (status == -1) { fprintf(stderr, "*** Client error: unable to send\n"); return; } /* receive server's processing results on the string */ nbytes = recv(cfd, buffer, MAX_LEN-1, 0); if (nbytes == -1) { fprintf(stderr, "*** Client error: unable to receive\n"); return; } buffer[nbytes] = '\0'; printf("%s",buffer); fflush(stdout); } int main ( int argc, char *argv[] ) { char sip[16]; int cfd; strcpy(sip, (argc==2) ? argv[1] : DEFAULT_SERVER); cfd = serverConnect(sip); serverTalk(cfd); close(cfd); } /*** End of client.c ***/