blob: 6de383ddd08ba7a198b3e2c81d6710dc43a53811 [file] [log] [blame]
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00001// SPDX-License-Identifier: GPL-2.0
2#include <stdio.h>
3#include <assert.h>
4#include <linux/bpf.h>
5#include <bpf/bpf.h>
David Brazdil0f672f62019-12-10 10:32:29 +00006#include "libbpf.h"
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007#include "sock_example.h"
8#include <unistd.h>
9#include <arpa/inet.h>
10#include <sys/resource.h>
11
12struct pair {
13 __u64 packets;
14 __u64 bytes;
15};
16
17int main(int ac, char **argv)
18{
19 struct rlimit r = {RLIM_INFINITY, RLIM_INFINITY};
David Brazdil0f672f62019-12-10 10:32:29 +000020 struct bpf_object *obj;
21 int map_fd, prog_fd;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000022 char filename[256];
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000023 int i, sock;
David Brazdil0f672f62019-12-10 10:32:29 +000024 FILE *f;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000025
26 snprintf(filename, sizeof(filename), "%s_kern.o", argv[0]);
27 setrlimit(RLIMIT_MEMLOCK, &r);
28
David Brazdil0f672f62019-12-10 10:32:29 +000029 if (bpf_prog_load(filename, BPF_PROG_TYPE_SOCKET_FILTER,
30 &obj, &prog_fd))
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000031 return 1;
David Brazdil0f672f62019-12-10 10:32:29 +000032
33 map_fd = bpf_object__find_map_fd_by_name(obj, "hash_map");
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000034
35 sock = open_raw_sock("lo");
36
David Brazdil0f672f62019-12-10 10:32:29 +000037 assert(setsockopt(sock, SOL_SOCKET, SO_ATTACH_BPF, &prog_fd,
38 sizeof(prog_fd)) == 0);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000039
David Brazdil0f672f62019-12-10 10:32:29 +000040 f = popen("ping -4 -c5 localhost", "r");
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000041 (void) f;
42
43 for (i = 0; i < 5; i++) {
44 int key = 0, next_key;
45 struct pair value;
46
David Brazdil0f672f62019-12-10 10:32:29 +000047 while (bpf_map_get_next_key(map_fd, &key, &next_key) == 0) {
48 bpf_map_lookup_elem(map_fd, &next_key, &value);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000049 printf("ip %s bytes %lld packets %lld\n",
50 inet_ntoa((struct in_addr){htonl(next_key)}),
51 value.bytes, value.packets);
52 key = next_key;
53 }
54 sleep(1);
55 }
56 return 0;
57}