xdp (2) xdp_hello_world

本文在host上编写了一个简单XDP程序,在xdp中返回XDP_DROP,即丢掉所有的数据包。
用clang编译为.o文件。使用ip link命令加载到guest的网卡中。
在guset上使用ping guest主机上网卡,测试xdp程序的丢包功能。

实验环境

host:ubuntu18.04
guest:ubuntu server 18.04
guest 网卡使用桥接的模式与host通信。

实验目的

熟悉xdp程序运行流程。

编写xdp程序

新建sample.c.写入以下内容

#include <linux/bpf.h>
int main() {
  return XDP_DROP;
}

编译

编写make file

TARGET ?= sample
$(TARGET).o:$(TARGET).c
	clang -O2 -target bpf -c $^ -o $@
clean:
	rm $(TARGET).o

执行make编译,编译后生成了elf文件格式的sample.o,
查看文件格式

#file sample.o
sample.o: ELF 64-bit LSB relocatable, *unknown arch 0xf7* version 1 (SYSV), not stripped

查看符号链接

objdump -t sample/sample.o 

sample/sample.o:     file format elf64-little

SYMBOL TABLE:
0000000000000000 g       .text	0000000000000000 main

加载

xdp程序的加载可使用两种方式,一种是调用bcc的相关的函数加载,另一种是使用
ip link set 命令加载。
执行ip link help命令,可以看出:

 ip link set { DEVICE | dev DEVICE | group DEVGROUP }
 [ xdp { off |
				  object FILE [ section NAME ] [ verbose ] |
				  pinned FILE } ]

把程序传到guest上,使用ip link命令加载。

scp udp.o lin@192.168.0.130:/home/lin/
guest执行:
ip link set dev enp0s3 xdp obj sample.o sec .txt

效果

host ping guest, 无响应

#ping 192.168.0.130 -c 4
PING 192.168.0.130 (192.168.0.130) 56(84) bytes of data.

--- 192.168.0.130 ping statistics ---
4 packets transmitted, 0 received, 100% packet loss, time 3050ms

卸载

ip link set dev enp0s3 xdp off

卸载后通信恢复正常

#ping 192.168.0.130 -c 4
PING 192.168.0.130 (192.168.0.130) 56(84) bytes of data.
64 bytes from 192.168.0.130: icmp_seq=1 ttl=64 time=0.210 ms
64 bytes from 192.168.0.130: icmp_seq=2 ttl=64 time=0.480 ms
64 bytes from 192.168.0.130: icmp_seq=3 ttl=64 time=0.461 ms
^C
--- 192.168.0.130 ping statistics ---
3 packets transmitted, 3 received, 0% packet loss, time 2028ms
rtt min/avg/max/mdev = 0.210/0.383/0.480/0.125 ms

遇到的问题

在编译的过程中遇到头文件未找到的问题

  1. 指定操作系统头文件
In file included from /usr/include/linux/bpf.h:11:
/usr/include/linux/types.h:5:10: fatal error: ‘asm/types.h’ file not found
#include <asm/types.h>
^~~~~~~~~~~~~
1 error generated.

解决方法

root@lin:~# cd /usr/local/
root@lin:/usr/local# ln -s x86_64-linux-gnu/asm/ asm
  1. clang的问题
fatal error: sys/cdefs.h: No such file or directory
sudo apt-get purge libc6-dev
sudo apt-get install libc6-dev
sudo apt-get install libc6-dev-i386

总结

本文主要是xdp功能的尝鲜版,让大家对xdp程序有一个初步的认识。数据包解析,参数传递,流量转发
将会在后续的文章中给出。

posted @ 2019-12-03 15:48  linengier  阅读(1347)  评论(0编辑  收藏  举报