/************************************************************** * connection-oriented server programming * * Function: echo server (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 /* for accept() and connect() */ #include #include /* for perror() */ #include /* for htonl() */ #define LISTENQ 2 #define BSIZE 256 #define USAGE "./servertcp 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 listenfd, connfd; /* socket file descriptor */ int portno; socklen_t clilen; char buffer[BSIZE]; struct sockaddr_in serv_addr, cli_addr; int n; /* check the correctness of command-line inputs */ if (argc < 2) error(USAGE); /* create a listening socket */ listenfd = socket(PF_INET, SOCK_STREAM, 0); if (listenfd < 0) error("ERROR opening socket"); /* specify local address */ bzero((char *) &serv_addr, sizeof(serv_addr)); serv_addr.sin_family = AF_INET; serv_addr.sin_addr.s_addr = htonl(INADDR_ANY); portno = atoi(argv[1]); serv_addr.sin_port = htons(portno); /* bind the address to the listening socket */ if (bind(listenfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) error("ERROR on binding"); /* specify a queue length for the server */ listen(listenfd, LISTENQ); /* accept connections */ clilen = sizeof(cli_addr); connfd = accept(listenfd, (struct sockaddr *) &cli_addr, &clilen); if (connfd < 0) error("ERROR on accept"); /* start to receive data */ bzero(buffer, BSIZE); n = read(connfd, buffer, BSIZE-1); if (n < 0) error("ERROR reading from socket"); printf("Here is the message: %s\n", buffer); fflush(stdout); /* start to reply to client */ n = write(connfd, "I got your message", 18); if (n < 0) error("ERROR writing to socket"); return 0; }