previous | start | next

Iterative Echo Server with Processes

    1   /* 
    2    * echoserveri.c - An iterative echo server 
    3    */ 
    4   /* $begin echoserverimain */
    5   #include "csapp.h"
    6   
    7   void echo(int connfd);
    8   
    9   int main(int argc, char **argv) 
   10   {
   11       int listenfd, connfd, port, clientlen;
   12       struct sockaddr_in clientaddr;
   13       struct hostent *hp;
   14       char *haddrp;
   15       if (argc != 2) {
   16           fprintf(stderr, "usage: %s <port>\n", argv[0]);
   17           exit(0);
   18       }
   19       port = atoi(argv[1]);
   20   
   21       listenfd = Open_listenfd(port);
   22       while (1) {
   23           clientlen = sizeof(clientaddr);
   24           connfd = Accept(listenfd, (SA *)&clientaddr, &clientlen);
   25   
   26           /* determine the domain name and IP address of the client */
   27           hp = Gethostbyaddr((const char *)&clientaddr.sin_addr.s_addr, 
   28                              sizeof(clientaddr.sin_addr.s_addr), AF_INET);
   29           haddrp = inet_ntoa(clientaddr.sin_addr);
   30           printf("server connected to %s (%s)\n", hp->h_name, haddrp);
   31   
   32           echo(connfd);
   33           Close(connfd);
   34       }
   35       exit(0);
   36   }
   37   /* $end echoserverimain */


previous | start | next