0001
0002 #include <stdio.h>
0003 #include <assert.h>
0004 #include <linux/bpf.h>
0005 #include <bpf/bpf.h>
0006 #include <bpf/libbpf.h>
0007 #include "sock_example.h"
0008 #include <unistd.h>
0009 #include <arpa/inet.h>
0010
0011 int main(int ac, char **argv)
0012 {
0013 struct bpf_object *obj;
0014 struct bpf_program *prog;
0015 int map_fd, prog_fd;
0016 char filename[256];
0017 int i, sock, err;
0018 FILE *f;
0019
0020 snprintf(filename, sizeof(filename), "%s_kern.o", argv[0]);
0021
0022 obj = bpf_object__open_file(filename, NULL);
0023 if (libbpf_get_error(obj))
0024 return 1;
0025
0026 prog = bpf_object__next_program(obj, NULL);
0027 bpf_program__set_type(prog, BPF_PROG_TYPE_SOCKET_FILTER);
0028
0029 err = bpf_object__load(obj);
0030 if (err)
0031 return 1;
0032
0033 prog_fd = bpf_program__fd(prog);
0034 map_fd = bpf_object__find_map_fd_by_name(obj, "my_map");
0035
0036 sock = open_raw_sock("lo");
0037
0038 assert(setsockopt(sock, SOL_SOCKET, SO_ATTACH_BPF, &prog_fd,
0039 sizeof(prog_fd)) == 0);
0040
0041 f = popen("ping -4 -c5 localhost", "r");
0042 (void) f;
0043
0044 for (i = 0; i < 5; i++) {
0045 long long tcp_cnt, udp_cnt, icmp_cnt;
0046 int key;
0047
0048 key = IPPROTO_TCP;
0049 assert(bpf_map_lookup_elem(map_fd, &key, &tcp_cnt) == 0);
0050
0051 key = IPPROTO_UDP;
0052 assert(bpf_map_lookup_elem(map_fd, &key, &udp_cnt) == 0);
0053
0054 key = IPPROTO_ICMP;
0055 assert(bpf_map_lookup_elem(map_fd, &key, &icmp_cnt) == 0);
0056
0057 printf("TCP %lld UDP %lld ICMP %lld bytes\n",
0058 tcp_cnt, udp_cnt, icmp_cnt);
0059 sleep(1);
0060 }
0061
0062 return 0;
0063 }