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> 8 #include <sys/resource.h> 9 10 struct flow_keys { 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 { 27 struct rlimit r = {RLIM_INFINITY, RLIM_INFINITY}; 28 char filename[256]; 29 FILE *f; 30 int i, sock; 31 32 snprintf(filename, sizeof(filename), "%s_kern.o", argv[0]); 33 setrlimit(RLIMIT_MEMLOCK, &r); 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++) { 52 struct flow_keys key = {}, next_key; 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 } 70