Olaf Bohlen
2020-05-13 a030875d819fc645c3b2fe14be426be9c7d32671
commit | author | age
caef9a 1 /*********************
OB 2  * simple TCP-server *
3  *********************/
4 #include <fcntl.h>
5 #include <unistd.h>
6 #include <sys/socket.h>
7 #include <sys/types.h>
8 #include <stdlib.h>
9 #include <stdio.h>
10 #include <netdb.h>
11 #include <string.h>
12
13 int main(int argc, char **argv) {
14   unsigned short port;       /* port to bind to */
15   char buffer[80];           /* i/o buffer */
16   struct sockaddr_in client; /* ip address of client */
17   struct sockaddr_in server; /* ip address of server */
18   struct hostent *hostnm;    /* dest-hostname to connect to */
19   int s;                     /* socket */
20   int ns;                    /* socket connected to client */
21   int namelen;               /* length of client name */
22   int optval=1;      
23   int s_optlen=0;
24   ssize_t recvbytes;         /* received bytes */
25
26   /* check for needed parameters */
27   if(argc!=3) {
28     fprintf(stderr, "%s portnumber\n", argv[0]);
29     exit(1);
30   }
31   hostnm=gethostbyname(argv[1]);
32
33   /* port to int */
34   port=(unsigned short) atoi(argv[2]);
35
36   /* generating socket */
37   if((s=socket(AF_INET, SOCK_STREAM,0))<0){
38     perror("Error:");
39     exit(2);
40   }
41
42   /* set socket options so that we can reuse the port */
43   setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &optval, s_optlen);
44
45   /* bind to socket */
46   server.sin_family = AF_INET;
47   server.sin_port = htons(port);
48   server.sin_addr.s_addr = *((unsigned long *)hostnm->h_addr);
49
50   if(bind(s, (struct sockaddr *)&server, sizeof(server))<0){
51     perror("Error:");
52     exit(3);
53   }
54
55   /* waiting for connections */
56   if(listen(s,1)!=0){
57     perror("Error:");
58     exit(4);
59   }
60
61   /* get connection */
62   namelen=sizeof(client);
63
64   /* we loop forever here to avoid stopping the server */
65   while(1) {
66     if((ns=accept(s, (struct sockaddr *)&client, &namelen))==-1){
67       perror("Error:");
68       exit(5);
69     }
70
71     /* write welcome banner to user */
72     snprintf(buffer, 54, "Welcome to the echo server, type a single x to quit.\n");
73     send(ns, buffer, 54, 0);
74     /* loop until we get an x as first char */
75     do {
76       /* get messages */
77       recvbytes=recv(ns, buffer, sizeof(buffer), 0);
78       if(recvbytes  == -1){
79         perror("Error:");
80         exit(6);
81       }
82    
83       /* send answer */
84       if(send(ns, buffer, recvbytes, 0) <0){
85         perror("Error:");
86         exit(7);
87       }
88     } while (buffer[0] != 'x');
89
90     /* client session closed on request, say bye bye */
91     snprintf(buffer, 30, "Good bye, see you next time.\n");
92     send(ns, buffer, 30, 0);
93     
94     /* close connection */
95     close(ns);
96   }
97   
98   /* close listener */
99   close(s);
100   printf("server exiting\n");
101   return(0);
102 }