1 /****************************************************************
3 * Program echo_tcp_server.c:
4 * Elementary TCP server for echo service (port 7)
6 * Author: Simone Piccardi
11 * $Id: SimpleEchoTCPServer.c,v 1.1 2001/06/10 11:47:17 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 */
29 /* Subroutine declaration */
31 void SockEcho(int sockfd);
33 /* Program begining */
34 int main(int argc, char *argv[])
37 * Variables definition
41 struct sockaddr_in serv_add;
43 * Input section: decode parameters passed in the calling
47 opterr = 0; /* don't want writing to stderr */
48 while ( (i = getopt(argc, argv, "h")) != -1) {
54 printf("Wrong -h option use\n");
58 case '?': /* unrecognized options */
59 printf("Unrecognized options -%c\n",optopt);
61 default: /* should not reached */
65 /* ***********************************************************
67 * Options processing completed
71 * ***********************************************************/
73 if ( (list_fd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
74 perror("Socket creation error");
77 /* initialize address */
78 memset((void *)&serv_add, 0, sizeof(serv_add)); /* clear server address */
79 serv_add.sin_family = AF_INET; /* address type is INET */
80 serv_add.sin_port = htons(13); /* daytime port is 13 */
81 serv_add.sin_addr.s_addr = htonl(INADDR_ANY); /* connect from anywhere */
83 if (bind(list_fd, (struct sockaddr *)&serv_add, sizeof(serv_add)) < 0) {
87 /* listen on socket */
88 if (listen(list_fd, BACKLOG) < 0 ) {
89 perror("listen error");
92 /* handle echo to client */
94 /* accept connection */
95 if ( (conn_fd = accept(list_fd, NULL, NULL)) < 0) {
96 perror("accept error");
99 /* fork to handle connection */
100 if ( (pid = fork()) < 0 ){
101 perror("fork error");
104 if (pid == 0) { /* child */
105 close(list_fd); /* close listening socket */
106 SockEcho(conn_fd); /* handle echo */
108 } else { /* parent */
109 close(conn_fd); /* close connected socket */
112 /* normal exit, never reached */
116 * routine to print usage info and exit
119 printf("Simple daytime server\n");
121 printf(" daytimed [-h] \n");
122 printf(" -h print this help\n");
126 * routine to handle echo for connection
128 void SockEcho(int sockfd) {
129 char buffer[MAXLINE];
132 /* main loop, reading 0 char means client close connection */
133 while ( (nread = SockRead(sockfd, buffer, MAXLINE)) != 0) {
134 nwrite = SockWrite(sockfd, buffer, nread);