eBPF网络入门
主要实现的功能收到网络数据包时写Hello World和跟踪管道的计数器。
#include <linux/bpf.h>
#include <bpf/bpf_helpers.h>
int counter = 0;
SEC("xdp")
int hello(struct xdp_md *ctx) {
bpf_printk("Hello World %d", counter);
counter++;
return XDP_PASS;
}
char LICENSE[] SEC("license") = "Dual BSD/GPL";
程序保存为hello-func.bpf.c
编译:clang -target bpf -I/usr/include/x86_64-linux-gnu -O2 -o hello.bpf.o -c hello.bpf.c
将程序加载到内核
用bpftool攻击将程序加载到内核:bpftool prog load hello.bpf.o /sys/fs/bpf/hello
查看是否加载成功:sudo ls /sys/fs/bpf
检查加载程序
用bpftool prog list 查看程序是否加载成功
bpftool prog show id xx --pretty ,将配置文件展示成json格式。
用bpftool来查看转换后的字节码
sudo bpftool prog dump xlated name hello
将时间加载到网卡
sudo bpftool net attach xdp id xx dev eth0
查看已加载的程序
sudo bpftool net list / ip link
查看输出
sudo cat /sys/kernel/debug/tracing/trace_pipe
分离程序
从网卡上删除程序
sudo bpftool net detach xdp dev eth0
卸载程序
rm /sys/fs/bpf/hello
rm /sys/fs/bpf/hello
参考:https://learning.oreilly.com/library/view/learning-ebpf/9781098135119/ch02.html#running_quotation_markhello_worldquotat