Aggiornamento note copyright
[gapil.git] / listati / TCP_cunc_daytimed.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         len = sizeof(client);
22         if ( (conn_fd = accept(list_fd, (struct sockaddr *)&client, &len)) 
23              <0 ) {
24             perror("accept error");
25             exit(-1);
26         }
27         /* fork to handle connection */
28         if ( (pid = fork()) < 0 ){
29             perror("fork error");
30             exit(-1);
31         }
32         if (pid == 0) {                 /* child */
33             close(list_fd);
34             timeval = time(NULL);
35             snprintf(buffer, sizeof(buffer), "%.24s\r\n", ctime(&timeval));
36             if ( (write(conn_fd, buffer, strlen(buffer))) < 0 ) {
37                 perror("write error");
38                 exit(-1);
39             }
40             if (logging) {
41                 inet_ntop(AF_INET, &client.sin_addr, buffer, sizeof(buffer));
42                 printf("Request from host %s, port %d\n", buffer,
43                        ntohs(client.sin_port));
44             }
45             close(conn_fd);
46             exit(0);
47         } else {                        /* parent */
48             close(conn_fd);
49         }
50     }
51     /* normal exit, never reached */
52     exit(0);
53 }