1 // SPDX-License-Identifier: GPL-2.0-only
11 #include "network_helpers.h"
13 #define clean_errno() (errno == 0 ? "None" : strerror(errno))
14 #define log_err(MSG, ...) fprintf(stderr, "(%s:%d: errno: %s) " MSG "\n", \
15 __FILE__, __LINE__, clean_errno(), ##__VA_ARGS__)
17 struct ipv4_packet pkt_v4 = {
18 .eth.h_proto = __bpf_constant_htons(ETH_P_IP),
20 .iph.protocol = IPPROTO_TCP,
21 .iph.tot_len = __bpf_constant_htons(MAGIC_BYTES),
26 struct ipv6_packet pkt_v6 = {
27 .eth.h_proto = __bpf_constant_htons(ETH_P_IPV6),
28 .iph.nexthdr = IPPROTO_TCP,
29 .iph.payload_len = __bpf_constant_htons(MAGIC_BYTES),
34 int start_server(int family, int type)
36 struct sockaddr_storage addr = {};
40 if (family == AF_INET) {
41 struct sockaddr_in *sin = (void *)&addr;
43 sin->sin_family = AF_INET;
46 struct sockaddr_in6 *sin6 = (void *)&addr;
48 sin6->sin6_family = AF_INET6;
52 fd = socket(family, type | SOCK_NONBLOCK, 0);
54 log_err("Failed to create server socket");
58 if (bind(fd, (const struct sockaddr *)&addr, len) < 0) {
59 log_err("Failed to bind socket");
64 if (type == SOCK_STREAM) {
65 if (listen(fd, 1) < 0) {
66 log_err("Failed to listed on socket");
75 static const struct timeval timeo_sec = { .tv_sec = 3 };
76 static const size_t timeo_optlen = sizeof(timeo_sec);
78 int connect_to_fd(int family, int type, int server_fd)
80 struct sockaddr_storage addr;
81 socklen_t len = sizeof(addr);
84 fd = socket(family, type, 0);
86 log_err("Failed to create client socket");
90 if (setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &timeo_sec, timeo_optlen)) {
91 log_err("Failed to set SO_RCVTIMEO");
95 if (getsockname(server_fd, (struct sockaddr *)&addr, &len)) {
96 log_err("Failed to get server addr");
100 if (connect(fd, (const struct sockaddr *)&addr, len) < 0) {
101 log_err("Fail to connect to server with family %d", family);