blob: a44bf347bedd30a8f9e90a40d78fb3c1446ac062 [file] [log] [blame]
Sargun Dhilloncf9b1192016-07-25 05:55:02 -07001#include <stdio.h>
2#include <assert.h>
3#include <linux/bpf.h>
4#include <unistd.h>
5#include "libbpf.h"
6#include "bpf_load.h"
7#include <sys/socket.h>
8#include <string.h>
9#include <netinet/in.h>
10#include <arpa/inet.h>
11
12int main(int ac, char **argv)
13{
14 int serverfd, serverconnfd, clientfd;
15 socklen_t sockaddr_len;
16 struct sockaddr serv_addr, mapped_addr, tmp_addr;
17 struct sockaddr_in *serv_addr_in, *mapped_addr_in, *tmp_addr_in;
18 char filename[256];
19 char *ip;
20
21 serv_addr_in = (struct sockaddr_in *)&serv_addr;
22 mapped_addr_in = (struct sockaddr_in *)&mapped_addr;
23 tmp_addr_in = (struct sockaddr_in *)&tmp_addr;
24
25 snprintf(filename, sizeof(filename), "%s_kern.o", argv[0]);
26
27 if (load_bpf_file(filename)) {
28 printf("%s", bpf_log_buf);
29 return 1;
30 }
31
32 assert((serverfd = socket(AF_INET, SOCK_STREAM, 0)) > 0);
33 assert((clientfd = socket(AF_INET, SOCK_STREAM, 0)) > 0);
34
35 /* Bind server to ephemeral port on lo */
36 memset(&serv_addr, 0, sizeof(serv_addr));
37 serv_addr_in->sin_family = AF_INET;
38 serv_addr_in->sin_port = 0;
39 serv_addr_in->sin_addr.s_addr = htonl(INADDR_LOOPBACK);
40
41 assert(bind(serverfd, &serv_addr, sizeof(serv_addr)) == 0);
42
43 sockaddr_len = sizeof(serv_addr);
44 assert(getsockname(serverfd, &serv_addr, &sockaddr_len) == 0);
45 ip = inet_ntoa(serv_addr_in->sin_addr);
46 printf("Server bound to: %s:%d\n", ip, ntohs(serv_addr_in->sin_port));
47
48 memset(&mapped_addr, 0, sizeof(mapped_addr));
49 mapped_addr_in->sin_family = AF_INET;
50 mapped_addr_in->sin_port = htons(5555);
51 mapped_addr_in->sin_addr.s_addr = inet_addr("255.255.255.255");
52
53 assert(!bpf_update_elem(map_fd[0], &mapped_addr, &serv_addr, BPF_ANY));
54
55 assert(listen(serverfd, 5) == 0);
56
57 ip = inet_ntoa(mapped_addr_in->sin_addr);
58 printf("Client connecting to: %s:%d\n",
59 ip, ntohs(mapped_addr_in->sin_port));
60 assert(connect(clientfd, &mapped_addr, sizeof(mapped_addr)) == 0);
61
62 sockaddr_len = sizeof(tmp_addr);
63 ip = inet_ntoa(tmp_addr_in->sin_addr);
64 assert((serverconnfd = accept(serverfd, &tmp_addr, &sockaddr_len)) > 0);
65 printf("Server received connection from: %s:%d\n",
66 ip, ntohs(tmp_addr_in->sin_port));
67
68 sockaddr_len = sizeof(tmp_addr);
69 assert(getpeername(clientfd, &tmp_addr, &sockaddr_len) == 0);
70 ip = inet_ntoa(tmp_addr_in->sin_addr);
71 printf("Client's peer address: %s:%d\n",
72 ip, ntohs(tmp_addr_in->sin_port));
73
74 /* Is the server's getsockname = the socket getpeername */
75 assert(memcmp(&serv_addr, &tmp_addr, sizeof(struct sockaddr_in)) == 0);
76
77 return 0;
78}