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