-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtcpsrv.c
More file actions
98 lines (87 loc) · 2.45 KB
/
tcpsrv.c
File metadata and controls
98 lines (87 loc) · 2.45 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
90
91
92
93
94
95
96
97
98
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <strings.h>
#include <string.h>
// #define SRVPORT "49154"
struct msg_echo {
unsigned short seq;
unsigned short reserve;
char msg[32];
};
int main(int argc, char *argv[])
{
int sd, sd1, err, cnt;
struct addrinfo hints, *res;
struct sockaddr_storage sin;
struct msg_echo echo;
pid_t pid;
socklen_t sktlen, len;
char hbuf[NI_MAXHOST], sbuf[NI_MAXSERV];
if (argc != 2) {
fprintf(stderr, "Usage: ./tcpsrv <port number>\n");
exit(1);
}
memset(&hints, 0, sizeof hints);
hints.ai_flags = AI_PASSIVE;
hints.ai_socktype = SOCK_STREAM;
if ((err = getaddrinfo(NULL, argv[1], &hints, &res)) < 0) {
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(err));
exit(1);
}
if ((sd = socket(res->ai_family, res->ai_socktype,
res->ai_protocol)) < 0) {
perror("socket");
exit(1);
}
if (bind(sd, res->ai_addr, res->ai_addrlen) < 0) {
perror("bind");
exit(1);
}
freeaddrinfo(res);
if (listen(sd, 5) < 0) {
perror("lisen");
exit(1);
}
for (;;) {
sktlen = sizeof(struct sockaddr_storage);
if ((sd1 = accept(sd, (struct sockaddr *)&sin, &sktlen)) < 0) {
perror("accept");
exit(1);
}
pid = fork();
if (pid < 0) {
perror("fork");
exit(1);
} else if (pid != 0) {
continue;
}
if ((err = getnameinfo((struct sockaddr *)&sin, len, hbuf,
sizeof(hbuf), sbuf, sizeof(sbuf), 0)) < 0) {
fprintf(stderr, "getnameinfo: %s\n", gai_strerror(err));
exit(1);
}
for (;;) {
if ((cnt = recv(sd1, &echo, sizeof echo, 0)) < 0) {
perror("recv");
exit(1);
}
echo.msg[cnt - sizeof(unsigned short) * 2] = '\0';
printf("%d bytes recved: IP %s, port %s, seq %d, msg %s\n",
cnt, hbuf, sbuf, echo.seq, echo.msg);
echo.seq++;
if ((cnt = send(sd1, &echo, sizeof echo, 0)) < 0) {
perror("send");
exit(1);
}
printf("%d bytes sent\n", cnt);
}
close(sd1);
}
close(sd);
}