9af8cc772ba2c0a2122fa2672f21b18305bb025f
[gapil.git] / listati / ElemDaytimeTCPCuncServ.c
1 #include <sys/types.h>   /* predefined types */
2 #include <unistd.h>      /* include unix standard library */
3 #include <arpa/inet.h>   /* IP addresses conversion utililites */
4 #include <sys/socket.h>  /* socket library */
5 #include <stdio.h>       /* include standard I/O library */
6 #include <time.h>
7
8 int main(int argc, char *argv[])
9 {
10     int list_fd, conn_fd;
11     int i;
12     struct sockaddr_in serv_add, client;
13     char buffer[MAXLINE];
14     socklen_t len;
15     time_t timeval;
16     pid_t pid;
17     int logging=0;
18      ...
19     /* write daytime to client */
20     while (1) {
21         if ( (conn_fd = accept(list_fd, (struct sockaddr *)&client, &len)) 
22              <0 ) {
23             perror("accept error");
24             exit(-1);
25         }
26         /* fork to handle connection */
27         if ( (pid = fork()) < 0 ){
28             perror("fork error");
29             exit(-1);
30         }
31         if (pid == 0) {                 /* child */
32             close(list_fd);
33             timeval = time(NULL);
34             snprintf(buffer, sizeof(buffer), "%.24s\r\n", ctime(&timeval));
35             if ( (write(conn_fd, buffer, strlen(buffer))) < 0 ) {
36                 perror("write error");
37                 exit(-1);
38             }
39             if (logging) {
40                 inet_ntop(AF_INET, &client.sin_addr, buffer, sizeof(buffer));
41                 printf("Request from host %s, port %d\n", buffer,
42                        ntohs(client.sin_port));
43             }
44             close(conn_fd);
45             exit(0);
46         } else {                        /* parent */
47             close(conn_fd);
48         }
49     }
50     /* normal exit, never reached */
51     exit(0);
52 }