/* client2.c -- request-reply demo Compilation on cs: gcc -Wall -o client2 client2.c -lnsl -lsocket -lresolv */ #include #include #include #include #include #include #include #include #include #define MAXDATASIZE 100 // max number of bytes we can get at once int main(int argc, char *argv[]) { int sockfd, numbytes, reqnum = 1; char buf[MAXDATASIZE], req[MAXDATASIZE]; struct hostent *he; struct sockaddr_in their_addr; // connector's address information int port = 5555; // default port /* hostname as first parameter */ if (argc < 2) { fprintf(stderr,"usage: %s hostname [number] [port]\n", argv[0]); exit(1); } if ((he=gethostbyname(argv[1])) == NULL) { // get the host info perror("gethostbyname"); exit(1); } /* request as optional second parameter */ if (argc > 2) reqnum = atoi(argv[2]); /* port as optional third parameter */ if (argc > 3) port = atoi(argv[3]); /* get socket */ if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) { perror("socket"); exit(1); } /* construct host address struct */ their_addr.sin_family = AF_INET; // host byte order their_addr.sin_port = htons(port); // short, network byte order their_addr.sin_addr = *((struct in_addr *)he->h_addr); memset(&(their_addr.sin_zero), '\0', 8); // zero the rest of the struct /* connect */ if (connect(sockfd, (struct sockaddr *)&their_addr, sizeof(struct sockaddr)) == -1) { perror("connect"); exit(1); } /* construct and send request */ sprintf(req, "%d\015\012", reqnum); if (send(sockfd, req, strlen(req), 0) == -1) { perror("send"); exit(1); } /* receive until revc returns 0 (connection closed) (or -1 (error)) */ printf("Receiving:\n"); while ((numbytes = recv(sockfd, buf, MAXDATASIZE-1, 0))) { if (numbytes == -1) { perror("recv"); exit(1); } buf[numbytes] = '\0'; /* terminate string */ fputs(buf, stdout); } close(sockfd); return 0; }