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
|
#define _GNU_SOURCE
#include "cptc.h"
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <curl/curl.h>
#include <curl/easy.h>
#define error(text, status) \
do \
{ \
perror(text); \
exit(status); \
} while (0) \
void CPTC(const char *ip, in_port_t port, unsigned id)
{
struct sockaddr_in addr, peer;
socklen_t peer_size;
int fd, peerfd;
curl_easy_init();
if ((fd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
error("socket()", 1);
if ((setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &(int){1}, sizeof(int))) < 0)
error("setsockopt()", 1);
if ((setsockopt(fd, SOL_SOCKET, SO_REUSEPORT, &(int){1}, sizeof(int))) < 0)
error("setsockopt()", 1);
addr = (struct sockaddr_in)
{
.sin_addr.s_addr = inet_addr(ip),
.sin_port = htons(port),
.sin_family = AF_INET,
};
if (bind(fd, (struct sockaddr *)&addr, sizeof(addr)) < 0)
error("bind()", 1);
if (listen(fd, 128) == -1)
error("listen()", 3);
printf("Started serving at %s:%d\n", ip, port);
for (;;)
{
peer_size = sizeof(peer);
if ((peerfd = accept(fd, (struct sockaddr *)&peer, &peer_size)) < 0)
{
perror("accept()");
continue;
}
printf("Connection from %s:%u!\n", inet_ntoa(peer.sin_addr), peer.sin_port);
CPTC_requestHandler(peerfd, id);
close(peerfd);
}
}
|