-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.c
More file actions
89 lines (76 loc) · 1.85 KB
/
server.c
File metadata and controls
89 lines (76 loc) · 1.85 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
81
82
83
84
85
86
87
88
89
// Source: https://book.systemsapproach.org/foundation/software.html
// sudo lsof -i :5432
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <netinet/in.h>
#include <netdb.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <assert.h>
#define SERVER_PORT 5432
#define MAX_PENDING 5
int main(int argc, const char *argv[])
{
struct sockaddr_in sin;
unsigned char buf[64];
socklen_t addr_len;
int s, new_s;
size_t i;
size_t n;
size_t total_bytes_received = 0;
size_t num_packets = 100000;
int packets = 0;
struct timeval start, end;
unsigned long long elapsed;
/* build address data structure */
bzero((char *)&sin, sizeof(sin));
sin.sin_family = AF_INET;
sin.sin_addr.s_addr = INADDR_ANY;
sin.sin_port = htons(SERVER_PORT);
/* setup passive open */
if ((s = socket(PF_INET, SOCK_STREAM, 0)) < 0) {
perror("socket failed");
exit(1);
}
if ((bind(s, (struct sockaddr *)&sin, sizeof(sin))) < 0) {
perror("bind failed");
exit(1);
}
if (listen(s, MAX_PENDING) < 0) {
perror("listen failed");
exit(1);
}
if ((new_s = accept(s, (struct sockaddr *)&sin, &addr_len)) < 0) {
perror("accept failed");
exit(1);
}
gettimeofday(&start, NULL);
do {
n = recv(new_s, buf, sizeof(buf), 0);
for (i = 0; i < n; i++) {
if (buf[0] != 0x7f) {
printf("data error\n");
exit(0);
}
}
packets++;
if ((packets % 1000) == 0) {
printf("completed %d packets\n", packets);
}
total_bytes_received += n;
}
while (n > 0);
if (total_bytes_received != num_packets * 64) {
printf("error: couldn't receive all packets\n");
exit(0);
}
gettimeofday(&end, NULL);
elapsed = (end.tv_sec * 1000000) + end.tv_usec - (start.tv_sec * 1000000) - start.tv_usec;
printf("%d packets received in %lld milliseconds\n", packets, elapsed / 1000);
close(new_s);
close(s);
return 0;
}