1 /****************************************************************
3 * Program ElemDaytimeTCPCuncServ.c
4 * Elementary TCP cuncurrent server for daytime service (port 13)
6 * Author: Simone Piccardi
11 * $Id: ElemDaytimeTCPCuncServ.c,v 1.1 2001/05/19 20:47:03 piccardi Exp $
13 ****************************************************************/
15 * Include needed headers
17 #include <sys/types.h> /* predefined types */
18 #include <unistd.h> /* include unix standard library */
19 #include <arpa/inet.h> /* IP addresses conversion utiliites */
20 #include <sys/socket.h> /* socket library */
21 #include <stdio.h> /* include standard I/O library */
28 int main(int argc, char *argv[])
31 * Variables definition
35 struct sockaddr_in serv_add, client;
42 * Input section: decode parameters passed in the calling
45 opterr = 0; /* don't want writing to stderr */
46 while ( (i = getopt(argc, argv, "hv")) != -1) {
52 printf("Wrong -h option use\n");
56 case '?': /* unrecognized options */
57 printf("Unrecognized options -%c\n",optopt);
64 default: /* should not reached */
69 /* ***********************************************************
71 * Options processing completed
75 * ***********************************************************/
77 if ( (list_fd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
78 perror("Socket creation error");
81 /* initialize address */
82 memset((void *)&serv_add, 0, sizeof(serv_add)); /* clear server address */
83 serv_add.sin_family = AF_INET; /* address type is INET */
84 serv_add.sin_port = htons(13); /* daytime port is 13 */
85 serv_add.sin_addr.s_addr = htonl(INADDR_ANY); /* connect from anywhere */
87 if (bind(list_fd, (struct sockaddr *)&serv_add, sizeof(serv_add)) < 0) {
91 /* listen on socket */
92 if (listen(list_fd, BACKLOG) < 0 ) {
93 perror("listen error");
96 /* write daytime to client */
98 if ( (conn_fd = accept(list_fd, (struct sockaddr *)&client, &len))
100 perror("accept error");
103 /* fork to handle connection */
104 if ( (pid = fork()) < 0 ){
105 perror("fork error");
108 if (pid == 0) { /* child */
110 timeval = time(NULL);
111 snprintf(buffer, sizeof(buffer), "%.24s\r\n", ctime(&timeval));
112 if ( (write(conn_fd, buffer, strlen(buffer))) < 0 ) {
113 perror("write error");
117 inet_ntop(AF_INET, &client.sin_addr, buffer, sizeof(buffer));
118 printf("Request from host %s, port %d\n", buffer,
119 ntohs(client.sin_port));
123 } else { /* parent */
127 /* normal exit, never reached */
131 * routine to print usage info and exit
134 printf("Simple daytime server\n");
136 printf(" daytimed [-hv] \n");
137 printf(" -h print this help\n");
138 printf(" -v print request source on stdout\n");