7 #include <sys/socket.h>
9 #include <netinet/in.h>
10 #include <arpa/inet.h>
12 int main(int ac
, char **argv
)
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
;
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
;
25 snprintf(filename
, sizeof(filename
), "%s_kern.o", argv
[0]);
27 if (load_bpf_file(filename
)) {
28 printf("%s", bpf_log_buf
);
32 assert((serverfd
= socket(AF_INET
, SOCK_STREAM
, 0)) > 0);
33 assert((clientfd
= socket(AF_INET
, SOCK_STREAM
, 0)) > 0);
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
);
41 assert(bind(serverfd
, &serv_addr
, sizeof(serv_addr
)) == 0);
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
));
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");
53 assert(!bpf_update_elem(map_fd
[0], &mapped_addr
, &serv_addr
, BPF_ANY
));
55 assert(listen(serverfd
, 5) == 0);
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);
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
));
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
));
74 /* Is the server's getsockname = the socket getpeername */
75 assert(memcmp(&serv_addr
, &tmp_addr
, sizeof(struct sockaddr_in
)) == 0);