1 /****************************************************************
3 * Program echo_tcp_server.c:
4 * Elementary TCP server for echo service (port 7)
6 * Author: Simone Piccardi
11 * $Id: ElemEchoTCPServer.c,v 1.2 2001/06/20 22:03:37 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 /* Subroutines declaration */
31 void ServEcho(int sockfd);
32 /* Program beginning */
33 int main(int argc, char *argv[])
36 * Variables definition
40 struct sockaddr_in serv_add;
42 * Input section: decode parameters passed in the calling
46 opterr = 0; /* don't want writing to stderr */
47 while ( (i = getopt(argc, argv, "h")) != -1) {
53 printf("Wrong -h option use\n");
57 case '?': /* unrecognized options */
58 printf("Unrecognized options -%c\n",optopt);
60 default: /* should not reached */
64 /* ***********************************************************
66 * Options processing completed
70 * ***********************************************************/
72 if ( (list_fd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
73 perror("Socket creation error");
76 /* initialize address */
77 memset((void *)&serv_add, 0, sizeof(serv_add)); /* clear server address */
78 serv_add.sin_family = AF_INET; /* address type is INET */
79 serv_add.sin_port = htons(7); /* echo port is 7 */
80 serv_add.sin_addr.s_addr = htonl(INADDR_ANY); /* connect from anywhere */
82 if (bind(list_fd, (struct sockaddr *)&serv_add, sizeof(serv_add)) < 0) {
86 /* listen on socket */
87 if (listen(list_fd, BACKLOG) < 0 ) {
88 perror("listen error");
91 /* handle echo to client */
93 /* accept connection */
94 if ( (conn_fd = accept(list_fd, NULL, NULL)) < 0) {
95 perror("accept error");
98 /* fork to handle connection */
99 if ( (pid = fork()) < 0 ){
100 perror("fork error");
103 if (pid == 0) { /* child */
104 close(list_fd); /* close listening socket */
105 SockEcho(conn_fd); /* handle echo */
107 } else { /* parent */
108 close(conn_fd); /* close connected socket */
111 /* normal exit, never reached */
115 * routine to print usage info and exit
118 printf("Simple daytime server\n");
120 printf(" daytimed [-h] \n");
121 printf(" -h print this help\n");
125 * routine to handle echo for connection
127 void ServEcho(int sockfd) {
128 char buffer[MAXLINE];
131 /* main loop, reading 0 char means client close connection */
132 while ( (nread = read(sockfd, buffer, MAXLINE)) != 0) {
133 printf("Letti %d bytes, %s ", nread, buffer);
134 nwrite = SockWrite(sockfd, buffer, nread);