Back to home page

OSCL-LXR

 
 

    


0001 // SPDX-License-Identifier: GPL-2.0
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 struct pair {
0012     __u64 packets;
0013     __u64 bytes;
0014 };
0015 
0016 int main(int ac, char **argv)
0017 {
0018     struct bpf_program *prog;
0019     struct bpf_object *obj;
0020     int map_fd, prog_fd;
0021     char filename[256];
0022     int i, sock, err;
0023     FILE *f;
0024 
0025     snprintf(filename, sizeof(filename), "%s_kern.o", argv[0]);
0026     obj = bpf_object__open_file(filename, NULL);
0027     if (libbpf_get_error(obj))
0028         return 1;
0029 
0030     prog = bpf_object__next_program(obj, NULL);
0031     bpf_program__set_type(prog, BPF_PROG_TYPE_SOCKET_FILTER);
0032 
0033     err = bpf_object__load(obj);
0034     if (err)
0035         return 1;
0036 
0037     prog_fd = bpf_program__fd(prog);
0038     map_fd = bpf_object__find_map_fd_by_name(obj, "hash_map");
0039 
0040     sock = open_raw_sock("lo");
0041 
0042     assert(setsockopt(sock, SOL_SOCKET, SO_ATTACH_BPF, &prog_fd,
0043               sizeof(prog_fd)) == 0);
0044 
0045     f = popen("ping -4 -c5 localhost", "r");
0046     (void) f;
0047 
0048     for (i = 0; i < 5; i++) {
0049         int key = 0, next_key;
0050         struct pair value;
0051 
0052         while (bpf_map_get_next_key(map_fd, &key, &next_key) == 0) {
0053             bpf_map_lookup_elem(map_fd, &next_key, &value);
0054             printf("ip %s bytes %lld packets %lld\n",
0055                    inet_ntoa((struct in_addr){htonl(next_key)}),
0056                    value.bytes, value.packets);
0057             key = next_key;
0058         }
0059         sleep(1);
0060     }
0061     return 0;
0062 }