nse_server.c

Go to the documentation of this file.
00001 #include <string.h>
00002 #include <sys/types.h>
00003 #include <unistd.h>
00004 
00005 #include "echo.h"
00006 #include "proxylib.h"
00007 
00008 int ns_errno;
00009 
00010 #define DEFAULT_PORT 12345
00011 
00012 int main(int argc, char **argv)
00013 {
00014   int listenfd, connfd;
00015   pid_t childpid;
00016   short port;
00017   socklen_t clilen;
00018   struct sockaddr_in cliaddr, servaddr;
00019   void sig_chld(int);
00020 
00021   if (argc == 2)
00022     port = atoi(argv[1]);
00023   else
00024     port = DEFAULT_PORT;
00025 
00026   proxy_init("nse.cfg");
00027 
00028   if ((listenfd = proxy_socket(AF_INET, SOCK_STREAM, 0)) < 0) {
00029     perror("Failed to create socket");
00030     exit(EXIT_FAILURE);
00031   }
00032 
00033   memset(&servaddr, 0x0, sizeof(servaddr));
00034   servaddr.sin_family = AF_INET;
00035   servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
00036   servaddr.sin_port = htons(port);
00037 
00038   if (proxy_bind(listenfd, (struct sockaddr *) &servaddr, sizeof(servaddr)) < 0) {
00039     perror("Failed to bind");
00040     exit(EXIT_FAILURE);
00041   }
00042 
00043   if (proxy_listen(listenfd, 20) < 0) {
00044     perror("Listen failed");
00045     exit(EXIT_FAILURE);
00046   }
00047 
00048   printf("Server listening on port %d\n", ntohs(servaddr.sin_port));
00049 
00050   signal(SIGCHLD, sig_chld);    /* must call waitpid() */
00051 
00052   for (;;) {
00053     clilen = sizeof(cliaddr);
00054     if ((connfd = proxy_accept(listenfd, (struct sockaddr *) &cliaddr, &clilen)) < 0) {
00055       if (errno == EINTR)
00056     continue;       /* back to for() */
00057       else {
00058     perror("accept error");
00059     exit(-1);
00060       }
00061     }
00062 
00063     if ((childpid = fork()) == 0) { /* child process */
00064       proxy_close(listenfd);    /* close listening socket */
00065       str_echo(connfd);     /* process the request */
00066       exit(0);
00067     }
00068     close(connfd);      /* parent closes connected socket */
00069   }
00070 }
00071 
00072 void sig_chld(int signo)
00073 {
00074   pid_t pid;
00075   int stat;
00076 
00077   while ((pid = waitpid(-1, &stat, WNOHANG)) > 0)
00078     printf("child %d terminated\n", (int)pid);
00079   return;
00080 }
00081 
00082 void str_echo(int sockfd)
00083 {
00084   ssize_t n;
00085   char line[MAXLINE];
00086 
00087   for (;;) {
00088     if ((n = Readline(sockfd, line, MAXLINE)) == 0)
00089       return;           /* connection closed by other end */
00090 
00091     Writen(sockfd, line, n);
00092   }
00093 }