blob: 3fcfd8c4b2a3c69da6a4719559cdd4edbbca0b30 [file] [log] [blame]
Alexei Starovoitov530b2c82015-05-19 16:59:06 -07001#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 Tueb88d5852016-06-21 21:05:58 -07008#include <sys/resource.h>
Alexei Starovoitov530b2c82015-05-19 16:59:06 -07009
Naveen N. Rao2b064ff2016-09-24 02:10:04 +053010struct bpf_flow_keys {
Alexei Starovoitov530b2c82015-05-19 16:59:06 -070011 __be32 src;
12 __be32 dst;
13 union {
14 __be32 ports;
15 __be16 port16[2];
16 };
17 __u32 ip_proto;
18};
19
20struct pair {
21 __u64 packets;
22 __u64 bytes;
23};
24
25int main(int argc, char **argv)
26{
William Tueb88d5852016-06-21 21:05:58 -070027 struct rlimit r = {RLIM_INFINITY, RLIM_INFINITY};
Alexei Starovoitov530b2c82015-05-19 16:59:06 -070028 char filename[256];
29 FILE *f;
30 int i, sock;
31
32 snprintf(filename, sizeof(filename), "%s_kern.o", argv[0]);
William Tueb88d5852016-06-21 21:05:58 -070033 setrlimit(RLIMIT_MEMLOCK, &r);
Alexei Starovoitov530b2c82015-05-19 16:59:06 -070034
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. Rao2b064ff2016-09-24 02:10:04 +053052 struct bpf_flow_keys key = {}, next_key;
Alexei Starovoitov530b2c82015-05-19 16:59:06 -070053 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}