-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.c
More file actions
80 lines (71 loc) · 1.53 KB
/
server.c
File metadata and controls
80 lines (71 loc) · 1.53 KB
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
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <signal.h>
#include <string.h>
#define BUFSIZE 1024
char buf[BUFSIZE];
void serve(int s)
{
int n;
n = read(s, buf, BUFSIZE);
if (n == -1)
perror("read");
else
printf("%s\n", buf);
}
int main(int argc, char *argv[])
{
int s;
struct sockaddr_in myaddr;
int optval;
if (argc != 2) {
fprintf(stderr, "Usage: %s <port>\n", argv[0]);
exit(1);
}
if ((s = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
perror("socket");
exit(1);
}
/*
* Socket option SO_REUSEADDR: Allow bind(), even when old
* protocol instances are still using the address.
*/
optval = 1;
if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval))) {
perror("setsockopt");
exit(1);
}
memset(&myaddr, 0, sizeof(myaddr));
myaddr.sin_family = AF_INET;
myaddr.sin_port = htons(atoi(argv[1]));
myaddr.sin_addr.s_addr = INADDR_ANY;
if (bind(s, (struct sockaddr *)&myaddr, sizeof(myaddr))) {
perror("bind");
exit(1);
}
if (listen(s, SOMAXCONN)) {
perror("listen");
exit(1);
}
while (1) {
int new_s;
struct sockaddr_in claddr;
int claddrlen;
claddrlen = sizeof(claddr);
if ((new_s =
accept(s, (struct sockaddr *)&claddr, &claddrlen)) < 0) {
perror("accept");
continue;
}
if (fork()) { /* Parent process */
close(new_s); /* New socket is used by child process only. */
} else { /* Child process */
close(s); /* Old socket is used by parent process only. */
serve(s);
exit(0);
}
}
}