1 /* eBPF example program:
2 * - creates arraymap in kernel with key 4 bytes and value 8 bytes
4 * - loads eBPF program:
5 * r0 = skb->data[ETH_HLEN + offsetof(struct iphdr, protocol)];
6 * *(u32*)(fp - 4) = r0;
7 * // assuming packet is IPv4, lookup ip->proto in a map
8 * value = bpf_map_lookup_elem(map_fd, fp - 4);
10 * (*(u64*)value) += 1;
12 * - attaches this program to eth0 raw socket
14 * - every second user space reads map[tcp], map[udp], map[icmp] to see
15 * how many packets of given protocol were seen on eth0
20 #include <linux/bpf.h>
24 #include <sys/socket.h>
25 #include <arpa/inet.h>
26 #include <linux/if_ether.h>
30 #include "sock_example.h"
32 char bpf_log_buf[BPF_LOG_BUF_SIZE];
34 static int test_sock(void)
36 int sock = -1, map_fd, prog_fd, i, key;
37 long long value = 0, tcp_cnt, udp_cnt, icmp_cnt;
39 map_fd = bpf_create_map(BPF_MAP_TYPE_ARRAY, sizeof(key), sizeof(value),
42 printf("failed to create map '%s'\n", strerror(errno));
46 struct bpf_insn prog[] = {
47 BPF_MOV64_REG(BPF_REG_6, BPF_REG_1),
48 BPF_LD_ABS(BPF_B, ETH_HLEN + offsetof(struct iphdr, protocol) /* R0 = ip->proto */),
49 BPF_STX_MEM(BPF_W, BPF_REG_10, BPF_REG_0, -4), /* *(u32 *)(fp - 4) = r0 */
50 BPF_MOV64_REG(BPF_REG_2, BPF_REG_10),
51 BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), /* r2 = fp - 4 */
52 BPF_LD_MAP_FD(BPF_REG_1, map_fd),
53 BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
54 BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, 2),
55 BPF_MOV64_IMM(BPF_REG_1, 1), /* r1 = 1 */
56 BPF_RAW_INSN(BPF_STX | BPF_XADD | BPF_DW, BPF_REG_0, BPF_REG_1, 0, 0), /* xadd r0 += r1 */
57 BPF_MOV64_IMM(BPF_REG_0, 0), /* r0 = 0 */
60 size_t insns_cnt = sizeof(prog) / sizeof(struct bpf_insn);
62 prog_fd = bpf_load_program(BPF_PROG_TYPE_SOCKET_FILTER, prog, insns_cnt,
63 "GPL", 0, bpf_log_buf, BPF_LOG_BUF_SIZE);
65 printf("failed to load prog '%s'\n", strerror(errno));
69 sock = open_raw_sock("lo");
71 if (setsockopt(sock, SOL_SOCKET, SO_ATTACH_BPF, &prog_fd,
72 sizeof(prog_fd)) < 0) {
73 printf("setsockopt %s\n", strerror(errno));
77 for (i = 0; i < 10; i++) {
79 assert(bpf_map_lookup_elem(map_fd, &key, &tcp_cnt) == 0);
82 assert(bpf_map_lookup_elem(map_fd, &key, &udp_cnt) == 0);
85 assert(bpf_map_lookup_elem(map_fd, &key, &icmp_cnt) == 0);
87 printf("TCP %lld UDP %lld ICMP %lld packets\n",
88 tcp_cnt, udp_cnt, icmp_cnt);
93 /* maps, programs, raw sockets will auto cleanup on process exit */
101 f = popen("ping -c5 localhost", "r");