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
|
/* usamos isso pra ter acesso ao `getaddrinfo()` e similares */
/* sera que da pra programar sockets sem usar? */
#ifndef _POSIX_C_SOURCE
#define _POSIX_C_SOURCE 200112L
#endif
#include<stdio.h>
#include<arpa/inet.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netdb.h>
#include<string.h>
#include<stdlib.h>
#include<unistd.h>
#include<errno.h>
#define ADDR NULL
#define PORT "9123"
#define BUFSIZE 32
#define BACKLOG 10
int main()
{
int gai_status, so_status, bind_status, listen_status, sockfd;
struct addrinfo hints = {
.ai_family = AF_UNSPEC,
.ai_socktype = SOCK_STREAM,
};
struct addrinfo *res;
gai_status = getaddrinfo(ADDR, PORT, &hints, &res);
if (gai_status != 0) {
fprintf(stderr, "gai error: %s.\n", gai_strerror(gai_status));
exit(1);
}
sockfd = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
if (sockfd < 0) {
fprintf(stderr, "socket error: %d.\n", errno);
exit(1);
}
/* nao tem uma maneira boa de explicar isso. essas linhas garantem que o
* mesmo socket possa ser reutilizado sem erros de bind. */
int yes = 1;
so_status = setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof yes);
if (so_status < 0) {
fprintf(stderr, "sockopt error: %d.\n", errno);
exit(1);
}
bind_status = bind(sockfd, res->ai_addr, res->ai_addrlen);
if (bind_status < 0) {
fprintf(stderr, "bind error: %d.\n", errno);
exit(1);
}
listen_status = listen(sockfd, BACKLOG);
if (listen_status < 0) {
fprintf(stderr, "listen error: %d.\n", errno);
exit(1);
}
/* loop principal: fica ouvindo conexões que chegam na porta PORT */
while (1) {
int client_sockfd = accept(sockfd, res->ai_addr, &res->ai_addrlen);
if (client_sockfd < 0) {
fprintf(stderr, "accept error: %d.\n", errno);
exit(1);
}
char buf[BUFSIZE];
while (1) {
ssize_t msg_len = recv(client_sockfd, buf, BUFSIZE, 0);
if (msg_len < 0) {
fprintf(stderr, "recv error: %d.\n", errno);
exit(1);
} else if (msg_len == 0) {
/* sem mais bytes a receber */
break;
}
ssize_t sent_len = send(client_sockfd, buf, msg_len, 0);
if (sent_len < 0) {
fprintf(stderr, "send error: %d.\n", errno);
exit(1);
}
}
}
freeaddrinfo(res);
return 0;
}
|