/************************************************************** * connection-oriented client programming * * Function: echo client (not iterative) * * Reference: Richard Stevens, Unix Network Programming, 1998 * * Created by: Hairong Qi **************************************************************/ #include /* for standard I/O */ #include /* for read() and write() */ #include /* for bzero() */ #include /* for atoi() */ #include #include /* for accept() and connect() */ #include /* for perror() */ #include /* for htonl() */ #include /* for gethostbyname() */ #define BSIZE 256 #define USAGE "./clienttcp server portno\n" /** ** output the error message and exit **/ void error(char *msg) { perror(msg); exit(1); } /** ** the main function **/ int main(int argc, char *argv[]) { int connfd; /* socket file descriptor */ int portno; struct hostent *server; char buffer[BSIZE]; struct sockaddr_in serv_addr; int n; /* check the correctness of command-line inputs */ if (argc < 3) error(USAGE); /* create a socket */ connfd = socket(PF_INET, SOCK_STREAM, 0); if (connfd < 0) error("ERROR opening socket"); /* specify local address */ bzero((char *) &serv_addr, sizeof(serv_addr)); serv_addr.sin_family = AF_INET; server = gethostbyname(argv[1]); if (server == NULL) error("ERROR, no such host\n"); bcopy((char *)server->h_addr, (char *)&serv_addr.sin_addr.s_addr, server->h_length); portno = atoi(argv[2]); serv_addr.sin_port = htons(portno); /* connect to server */ if (connect(connfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) error("ERROR connecting"); /* start sending message */ printf("Please enter the message: "); bzero(buffer, BSIZE); fgets(buffer, BSIZE-1, stdin); n = write(connfd, buffer, strlen(buffer)); if (n < 0) error("ERROR writing to socket"); bzero(buffer, BSIZE); n = read(connfd, buffer, BSIZE-1); if (n < 0) error("ERROR reading from socket"); printf("%s\n", buffer); fflush(stdout); return 0; }