blob: 3c83722877dc58aebd7e15f4a037f721e82cc2f4 [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>
Olivier Deprez157378f2022-04-04 15:47:50 +02006#include <bpf/libbpf.h>
Andrew Scullb4b6d4a2019-01-02 15:54:55 +00007#include "sock_example.h"
8#include <unistd.h>
9#include <arpa/inet.h>
10
11int main(int ac, char **argv)
12{
David Brazdil0f672f62019-12-10 10:32:29 +000013 struct bpf_object *obj;
14 int map_fd, prog_fd;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000015 char filename[256];
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000016 int i, sock;
David Brazdil0f672f62019-12-10 10:32:29 +000017 FILE *f;
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000018
19 snprintf(filename, sizeof(filename), "%s_kern.o", argv[0]);
20
David Brazdil0f672f62019-12-10 10:32:29 +000021 if (bpf_prog_load(filename, BPF_PROG_TYPE_SOCKET_FILTER,
22 &obj, &prog_fd))
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000023 return 1;
David Brazdil0f672f62019-12-10 10:32:29 +000024
25 map_fd = bpf_object__find_map_fd_by_name(obj, "my_map");
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000026
27 sock = open_raw_sock("lo");
28
David Brazdil0f672f62019-12-10 10:32:29 +000029 assert(setsockopt(sock, SOL_SOCKET, SO_ATTACH_BPF, &prog_fd,
30 sizeof(prog_fd)) == 0);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000031
David Brazdil0f672f62019-12-10 10:32:29 +000032 f = popen("ping -4 -c5 localhost", "r");
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000033 (void) f;
34
35 for (i = 0; i < 5; i++) {
36 long long tcp_cnt, udp_cnt, icmp_cnt;
37 int key;
38
39 key = IPPROTO_TCP;
David Brazdil0f672f62019-12-10 10:32:29 +000040 assert(bpf_map_lookup_elem(map_fd, &key, &tcp_cnt) == 0);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000041
42 key = IPPROTO_UDP;
David Brazdil0f672f62019-12-10 10:32:29 +000043 assert(bpf_map_lookup_elem(map_fd, &key, &udp_cnt) == 0);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000044
45 key = IPPROTO_ICMP;
David Brazdil0f672f62019-12-10 10:32:29 +000046 assert(bpf_map_lookup_elem(map_fd, &key, &icmp_cnt) == 0);
Andrew Scullb4b6d4a2019-01-02 15:54:55 +000047
48 printf("TCP %lld UDP %lld ICMP %lld bytes\n",
49 tcp_cnt, udp_cnt, icmp_cnt);
50 sleep(1);
51 }
52
53 return 0;
54}