1 /****************************************************************
3 * Program daytime_tcp_server.c:
4 * Elementary TCP server for daytime service (port 13)
6 * Author: Simone Piccardi
11 * $Id: SimpleDaytimeTCPServer.c,v 1.2 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;
39 * Input section: decode parameters passed in the calling
42 opterr = 0; /* don't want writing to stderr */
43 while ( (i = getopt(argc, argv, "h")) != -1) {
49 printf("Wrong -h option use\n");
53 case '?': /* unrecognized options */
54 printf("Unrecognized options -%c\n",optopt);
56 default: /* should not reached */
60 /* ***********************************************************
62 * Options processing completed
66 * ***********************************************************/
68 if ( (list_fd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
69 perror("Socket creation error");
72 /* initialize address */
73 memset((void *)&serv_add, 0, sizeof(serv_add)); /* clear server address */
74 serv_add.sin_family = AF_INET; /* address type is INET */
75 serv_add.sin_port = htons(13); /* daytime port is 13 */
76 serv_add.sin_addr.s_addr = htonl(INADDR_ANY); /* connect from anywhere */
78 if (bind(list_fd, (struct sockaddr *)&serv_add, sizeof(serv_add)) < 0) {
82 /* listen on socket */
83 if (listen(list_fd, BACKLOG) < 0 ) {
84 perror("listen error");
87 /* write daytime to client */
89 if ( (conn_fd = accept(list_fd, (struct sockaddr *) NULL, NULL)) <0 ) {
90 perror("accept error");
94 snprintf(buffer, sizeof(buffer), "%.24s\r\n", ctime(&timeval));
95 if ( (write(conn_fd, buffer, strlen(buffer))) < 0 ) {
96 perror("write error");
106 * routine to print usage info and exit
109 printf("Simple daytime server\n");
111 printf(" daytimed [-h] \n");
112 printf(" -h print this help\n");