Alexei Starovoitov | 530b2c8 | 2015-05-19 16:59:06 -0700 | [diff] [blame] | 1 | #include <stdio.h> |
| 2 | #include <assert.h> |
| 3 | #include <linux/bpf.h> |
| 4 | #include "libbpf.h" |
| 5 | #include "bpf_load.h" |
| 6 | #include <unistd.h> |
| 7 | #include <arpa/inet.h> |
William Tu | eb88d585 | 2016-06-21 21:05:58 -0700 | [diff] [blame] | 8 | #include <sys/resource.h> |
Alexei Starovoitov | 530b2c8 | 2015-05-19 16:59:06 -0700 | [diff] [blame] | 9 | |
Naveen N. Rao | 2b064ff | 2016-09-24 02:10:04 +0530 | [diff] [blame] | 10 | struct bpf_flow_keys { |
Alexei Starovoitov | 530b2c8 | 2015-05-19 16:59:06 -0700 | [diff] [blame] | 11 | __be32 src; |
| 12 | __be32 dst; |
| 13 | union { |
| 14 | __be32 ports; |
| 15 | __be16 port16[2]; |
| 16 | }; |
| 17 | __u32 ip_proto; |
| 18 | }; |
| 19 | |
| 20 | struct pair { |
| 21 | __u64 packets; |
| 22 | __u64 bytes; |
| 23 | }; |
| 24 | |
| 25 | int main(int argc, char **argv) |
| 26 | { |
William Tu | eb88d585 | 2016-06-21 21:05:58 -0700 | [diff] [blame] | 27 | struct rlimit r = {RLIM_INFINITY, RLIM_INFINITY}; |
Alexei Starovoitov | 530b2c8 | 2015-05-19 16:59:06 -0700 | [diff] [blame] | 28 | char filename[256]; |
| 29 | FILE *f; |
| 30 | int i, sock; |
| 31 | |
| 32 | snprintf(filename, sizeof(filename), "%s_kern.o", argv[0]); |
William Tu | eb88d585 | 2016-06-21 21:05:58 -0700 | [diff] [blame] | 33 | setrlimit(RLIMIT_MEMLOCK, &r); |
Alexei Starovoitov | 530b2c8 | 2015-05-19 16:59:06 -0700 | [diff] [blame] | 34 | |
| 35 | if (load_bpf_file(filename)) { |
| 36 | printf("%s", bpf_log_buf); |
| 37 | return 1; |
| 38 | } |
| 39 | |
| 40 | sock = open_raw_sock("lo"); |
| 41 | |
| 42 | assert(setsockopt(sock, SOL_SOCKET, SO_ATTACH_BPF, &prog_fd[4], |
| 43 | sizeof(__u32)) == 0); |
| 44 | |
| 45 | if (argc > 1) |
| 46 | f = popen("ping -c5 localhost", "r"); |
| 47 | else |
| 48 | f = popen("netperf -l 4 localhost", "r"); |
| 49 | (void) f; |
| 50 | |
| 51 | for (i = 0; i < 5; i++) { |
Naveen N. Rao | 2b064ff | 2016-09-24 02:10:04 +0530 | [diff] [blame] | 52 | struct bpf_flow_keys key = {}, next_key; |
Alexei Starovoitov | 530b2c8 | 2015-05-19 16:59:06 -0700 | [diff] [blame] | 53 | struct pair value; |
| 54 | |
| 55 | sleep(1); |
| 56 | printf("IP src.port -> dst.port bytes packets\n"); |
| 57 | while (bpf_get_next_key(map_fd[2], &key, &next_key) == 0) { |
| 58 | bpf_lookup_elem(map_fd[2], &next_key, &value); |
| 59 | printf("%s.%05d -> %s.%05d %12lld %12lld\n", |
| 60 | inet_ntoa((struct in_addr){htonl(next_key.src)}), |
| 61 | next_key.port16[0], |
| 62 | inet_ntoa((struct in_addr){htonl(next_key.dst)}), |
| 63 | next_key.port16[1], |
| 64 | value.bytes, value.packets); |
| 65 | key = next_key; |
| 66 | } |
| 67 | } |
| 68 | return 0; |
| 69 | } |