-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathecho_server.c
97 lines (83 loc) · 2 KB
/
echo_server.c
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
/* A simple echo server using TCP */
#include <stdio.h>
#include <sys/types.h>
#include <sys/unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <sys/signal.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <strings.h>
#define SERVER_TCP_PORT 3000 /* well-known port */
#define BUFLEN 256 /* buffer length */
int echod(int);
void reaper(int);
int main(int argc, char **argv)
{
int sd, new_sd, client_len, port;
struct sockaddr_in server, client;
setvbuf(stdout, NULL, _IONBF, 0); /*Make stdout unbuffered*/
switch(argc){
case 1:
port = SERVER_TCP_PORT;
break;
case 2:
port = atoi(argv[1]);
break;
default:
fprintf(stderr, "Usage: %s [port]\n", argv[0]);
exit(1);
}
/* Create a stream socket */
if ((sd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
fprintf(stderr, "Can't creat a socket\n");
exit(1);
}
/* Bind an address to the socket */
bzero((char *)&server, sizeof(struct sockaddr_in));
server.sin_family = AF_INET;
server.sin_port = htons(port);
server.sin_addr.s_addr = htonl(INADDR_ANY);
if (bind(sd, (struct sockaddr *)&server, sizeof(server)) == -1){
fprintf(stderr, "Can't bind name to socket\n");
exit(1);
}
/* queue up to 5 connect requests */
listen(sd, 5);
(void) signal(SIGCHLD, reaper);
while(1) {
client_len = sizeof(client);
new_sd = accept(sd, (struct sockaddr *)&client, &client_len);
if(new_sd < 0){
fprintf(stderr, "Can't accept client \n");
exit(1);
}
switch (fork()){
case 0: /* child */
(void) close(sd);
exit(echod(new_sd));
default: /* parent */
(void) close(new_sd);
break;
case -1:
fprintf(stderr, "fork: error\n");
}
}
}
/* echod program */
int echod(int sd)
{
char *bp, sbuf[BUFLEN];
int n, bytes_to_read;
printf("Send messages to client:\n");
while(n = read(0, sbuf, BUFLEN)) /* Get User Message */
write(sd, sbuf, n); /* Send it to the client */
close(sd);
return(0);
}
/* reaper */
void reaper(int sig)
{
int status;
while(wait3(&status, WNOHANG, (struct rusage *)0) >= 0);
}