AF_PACKET 原始套接字抓包实战:手写一个 mini-tcpdump(Permission denied 与 Protocol not supported 两个坑)
系列:Suricata 源码精读 · 网络开发(S01)环境:Ubuntu 20.04 / CentOS 7.9,gcc 9+,root 或
CAP_NET_RAW参考源码:src/source-af-packet.c
tcpdump 能用,但你未必知道它底下就干了三件事:socket(AF_PACKET, SOCK_RAW, ...)、bind() 到网卡、recvfrom() 死循环。本文从零手写一个 200 行的 mini-tcpdump,把这三个动作拆开讲清楚,并且顺手排掉新手最常撞的两个错。
一、先看两个必踩的报错
1.1 socket: Permission denied
ini
int fd = socket(AF_PACKET, SOCK_RAW, htons(ETH_P_ALL));
// 返回 -1,errno = EPERM (1) → "Operation not permitted"
原因 :AF_PACKET 的 SOCK_RAW 需要 CAP_NET_RAW 能力。非 root 用户即使是普通账号也拿不到。
三种解法,按推荐度排序:
bash
# 方案 A:给二进制单独授权(推荐,最小权限)
sudo setcap cap_net_raw,cap_net_admin+eip ./mini_tcpdump
getcap ./mini_tcpdump
# ./mini_tcpdump cap_net_admin,cap_net_raw=eip
# 方案 B:临时用 root(仅调试)
sudo ./mini_tcpdump eth0
# 方案 C:不要用 SOCK_RAW,改用 SOCK_DGRAM(见 1.3)
⚠️ 注意 setcap 有个隐蔽的坑:一旦给二进制设了文件能力,再 sudo 执行它,能力会被 sudo 的环境重置掉。所以要么始终非 root 跑,要么始终 root 跑,别混。
1.2 socket: Protocol not supported
scss
socket(AF_PACKET, SOCK_RAW, htons(ETH_P_ALL)); // errno = EPROTONOSUPPORT (93)
原因 :AF_PACKET 是 Linux 独有 的。在 macOS / FreeBSD 上编译运行必然失败 ------ BSD 系对应的是 BPF 设备(/dev/bpf0),macOS 上是 AF_LINK + 需先 ioctl(BIOCSETIF)。
如果你的代码要跨平台,正确姿势是:
arduino
#if defined(__linux__)
#define CAPTURE_LINUX_AFPACKET 1
#elif defined(__APPLE__) || defined(__FreeBSD__)
#define CAPTURE_BSD_BPF 1
#else
#error "unsupported platform"
#endif
另一个更隐蔽的原因 :htons(ETH_P_ALL) 写成了 ETH_P_ALL(漏了字节序转换)。ETH_P_ALL 是 0x0003,在小端机上不转字节序会被解释成 0x0300,内核找不到这个协议号,同样报 EPROTONOSUPPORT。这个错我在生产代码里见过两次,因为它只在某些内核版本上失败,代码 review 时极难发现。
1.3 SOCK_RAW 与 SOCK_DGRAM 的差别
source-af-packet.c 里对这两种模式都有处理。差别在于:
SOCK_RAW |
SOCK_DGRAM |
|
|---|---|---|
| 收到的数据 | 含链路层头(14 字节以太网头) | 已剥掉链路层头 |
| 源地址信息 | 在缓冲区开头 | 需 recvfrom() 的 sockaddr_ll |
| 能否发送 | 可以自己拼链路层头 | 内核代填,需 bind() 指定 |
| 权限 | CAP_NET_RAW |
同样需要(AF_PACKET 全族都要) |
自写抓包工具时 SOCK_RAW 更好,因为你通常想知道 VLAN tag、以太类型。但如果你只关心 IP 层,SOCK_DGRAM 少一层解析。
二、最小可运行版本
先上能跑的代码,再逐段讲。
c
// mini_tcpdump.c
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <signal.h>
#include <time.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <net/if.h>
#include <netinet/in.h>
#include <linux/if_packet.h>
#include <linux/if_ether.h>
#include <arpa/inet.h>
#define SNAP_LEN 65536
static volatile sig_atomic_t g_stop = 0;
static void on_sigint(int sig) { (void)sig; g_stop = 1; }
/* 打印 14 字节以太网头 */
static void dump_eth(const unsigned char *buf, int len)
{
if (len < (int)sizeof(struct ethhdr)) return;
const struct ethhdr *eth = (const struct ethhdr *)buf;
printf(" ETH src=%02x:%02x:%02x:%02x:%02x:%02x dst=%02x:%02x:%02x:%02x:%02x:%02x type=0x%04x\n",
eth->h_source[0], eth->h_source[1], eth->h_source[2],
eth->h_source[3], eth->h_source[4], eth->h_source[5],
eth->h_dest[0], eth->h_dest[1], eth->h_dest[2],
eth->h_dest[3], eth->h_dest[4], eth->h_dest[5],
ntohs(eth->h_proto));
}
/* 打印 IPv4 头 + TCP/UDP 端口 */
static void dump_ip(const unsigned char *buf, int len)
{
/* 跳过链路层头 */
const unsigned char *ip = buf + sizeof(struct ethhdr);
int iplen = len - sizeof(struct ethhdr);
if (iplen < 20 || (ip[0] >> 4) != 4) return;
int ihl = (ip[0] & 0x0f) * 4; /* 单位是 4 字节 */
int tot = (ip[2] << 8) | ip[3];
printf(" IP %u.%u.%u.%u -> %u.%u.%u.%u proto=%u len=%d\n",
ip[12], ip[13], ip[14], ip[15],
ip[16], ip[17], ip[18], ip[19],
ip[9], tot);
if (iplen < ihl + 4) return;
const unsigned char *l4 = ip + ihl;
if (ip[9] == 6) { /* TCP */
printf(" TCP %u -> %u\n",
(l4[0] << 8) | l4[1], (l4[2] << 8) | l4[3]);
} else if (ip[9] == 17) { /* UDP */
printf(" UDP %u -> %u\n",
(l4[0] << 8) | l4[1], (l4[2] << 8) | l4[3]);
}
}
int main(int argc, char *argv[])
{
if (argc != 2) {
fprintf(stderr, "usage: %s <ifname>\n", argv[0]);
return 1;
}
const char *ifname = argv[1];
/* ---- 步骤 1:创建原始套接字 ---- */
int fd = socket(AF_PACKET, SOCK_RAW, htons(ETH_P_ALL));
if (fd < 0) {
fprintf(stderr, "socket: %s\n", strerror(errno));
if (errno == EPERM)
fprintf(stderr, "hint: need CAP_NET_RAW, try: sudo setcap cap_net_raw,cap_net_admin+eip %s\n", argv[0]);
else if (errno == EPROTONOSUPPORT)
fprintf(stderr, "hint: AF_PACKET is Linux-only, or check htons(ETH_P_ALL)\n");
return 1;
}
/* ---- 步骤 2:取网卡 ifindex ---- */
struct ifreq ifr;
memset(&ifr, 0, sizeof(ifr));
strncpy(ifr.ifr_name, ifname, IFNAMSIZ - 1);
if (ioctl(fd, SIOCGIFINDEX, &ifr) < 0) {
fprintf(stderr, "ioctl SIOCGIFINDEX(%s): %s\n", ifname, strerror(errno));
close(fd);
return 1;
}
int ifindex = ifr.ifr_ifindex;
printf("ifindex of %s = %d\n", ifname, ifindex);
/* ---- 步骤 3:bind 到网卡 ---- */
struct sockaddr_ll sll;
memset(&sll, 0, sizeof(sll));
sll.sll_family = AF_PACKET;
sll.sll_protocol = htons(ETH_P_ALL);
sll.sll_ifindex = ifindex;
if (bind(fd, (struct sockaddr *)&sll, sizeof(sll)) < 0) {
fprintf(stderr, "bind: %s\n", strerror(errno));
close(fd);
return 1;
}
/* ---- 步骤 4:优雅退出 ---- */
struct sigaction sa;
memset(&sa, 0, sizeof(sa));
sa.sa_handler = on_sigint;
sigaction(SIGINT, &sa, NULL);
printf("capturing on %s, Ctrl-C to stop\n", ifname);
unsigned char *buf = malloc(SNAP_LEN);
if (!buf) { close(fd); return 1; }
unsigned long n = 0;
/* ---- 步骤 5:收包循环 ---- */
while (!g_stop) {
int len = recv(fd, buf, SNAP_LEN, 0);
if (len < 0) {
if (errno == EINTR) continue; /* 被信号打断,正常 */
fprintf(stderr, "recv: %s\n", strerror(errno));
break;
}
++n;
printf("#%lu len=%d\n", n, len);
dump_eth(buf, len);
dump_ip(buf, len);
if (n % 10 == 0) fflush(stdout);
}
printf("\ntotal %lu packets\n", n);
free(buf);
close(fd);
return 0;
}
编译:
bash
gcc -O2 -Wall -Wextra -o mini_tcpdump mini_tcpdump.c
sudo setcap cap_net_raw,cap_net_admin+eip ./mini_tcpdump
./mini_tcpdump lo
另开一个终端 ping 127.0.0.1,你应该能看到 ICMP 报文被打印出来。
三、逐段拆解:为什么是这五步
3.1 为什么 socket() 的第三个参数要 htons(ETH_P_ALL)
协议号在 socket() 里是 网络字节序 ,而 ETH_P_ALL 是主机字节序常量。这是 Linux 内核 API 里一个不一致的地方 ------ 只有 bind() 的时候才用主机序。
一个安全的写法是把两处都用 htons,保持对称:
ini
sll.sll_protocol = htons(ETH_P_ALL); /* bind 用,内核会再转一次 */
3.2 为什么一定要 bind(),不 bind 行不行
AF_PACKET 在没 bind 的情况下会收所有网卡 的报文。这在小机器上像是"能用",但在多网卡服务器上会收到一堆你不想要的流量,而且收包数量会成倍放大 ------ 因为同一份流量可能在多个接口上被重复捕获。
bind() 的实质是设置过滤器:sll_ifindex = 0 表示所有接口,具体值表示单一接口。
Suricata 的 AFPBindSocket() 做的就是这件事,并且额外支持 PACKET_FANOUT 分组(见 S04)。
3.3 SIOCGIFINDEX 为什么不直接用 if_nametoindex()
if_nametoindex() 是 glibc 提供的便捷函数,效果一样,代码更短:
ini
int ifindex = if_nametoindex(ifname); /* 失败返回 0 并设 errno */
Suricata 用的是 ioctl(SIOCGIFINDEX),原因是它在早期版本需要同时取 MTU 和 MAC (SIOCGIFMTU、SIOCGIFHWADDR),一次 ioctl 的 fd 已经开着就顺手都取了。你自写工具时用 if_nametoindex() 完全够。
3.4 为什么缓冲用 65536 而不是 1500
以太网 MTU 1500 只是单帧载荷上限,但:
- 开了巨型帧(Jumbo Frame)的环境 MTU 到 9000;
- 网卡开启 GRO/LRO 时,内核交上来的可能是合并后的超大包 ,单个
recv能到 64KB; - 缓冲区给小了,超出的部分会被静默截断 ,你拿到的
len比实际小,解析器就会错位。
SNAP_LEN 65536 是 tcpdump 的默认值,也是 pcap 里 MAXIMUM_SNAPLEN 的量级。别省这 64KB 内存。
3.5 recv 返回 -1 且 errno == EINTR 时必须 continue
信号(比如 Ctrl-C)会打断阻塞中的 recv。如果不判 EINTR 直接 break,会出现「按一次 Ctrl-C 程序立刻死,但抓包统计没打印」的现象。这是新手最常写的 bug 之一。
四、动手实验:三个必须自己跑一遍的验证
实验 1:验证 (SOCK_RAW) 真的带了链路层头
理论预期 :recv 返回的 len 应该比 IP 头里的 total length 大 14 字节(以太网头)。
步骤:
bash
# 终端 1
./mini_tcpdump lo
# 终端 2
ping -c 1 127.0.0.1
预期输出:
ini
#1 len=98
ETH src=00:00:00:00:00:00 dst=00:00:00:00:00:00 type=0x0800
IP 127.0.0.1 -> 127.0.0.1 proto=1 len=84
验证 :98 - 84 = 14 ✅ 正好是以太网头。
lo接口的 MAC 全是 0,这是正常的 ------ 回环设备没有真实硬件地址。
实验 2:验证 ETH_P_ALL 漏掉 htons 的后果
把 socket() 那行的 htons(ETH_P_ALL) 改成 ETH_P_ALL,重新编译运行:
预期 :在 x86(小端)上,socket() 应该返回 -1,errno = EPROTONOSUPPORT。
如果居然成功了 ,说明你的内核把 0x0300 也当成了一个合法协议号 ------ 那你会收到 零个报文 ,因为网卡上没有 0x0300 以太类型的流量。这个"静默失败"比报错更危险。
实验 3:对比 SOCK_RAW 与 SOCK_DGRAM
bash
sed 's/SOCK_RAW/SOCK_DGRAM/' mini_tcpdump.c > mini_tcpdump_dgram.c
gcc -O2 -o mini_tcpdump_dgram mini_tcpdump_dgram.c
sudo setcap cap_net_raw,cap_net_admin+eip ./mini_tcpdump_dgram
./mini_tcpdump_dgram lo
预期 :dump_eth() 打印的 type 会变成乱码(因为前 14 字节已经是 IP 头了),dump_ip() 会错位。这反证了 SOCK_DGRAM 已经剥掉了链路层头。
结论对照表:
| 观察项 | SOCK_RAW |
SOCK_DGRAM |
|---|---|---|
| 首 14 字节 | 以太网头 | IP 头 |
len vs IP total length |
大 14 | 相等 |
eth->h_proto |
0x0800 正常 |
乱码 |
五、排错表
| 现象 | 根因 | 解法 |
|---|---|---|
socket: Operation not permitted |
缺 CAP_NET_RAW |
setcap cap_net_raw,cap_net_admin+eip ./prog,注意别再 sudo |
socket: Protocol not supported |
① 非 Linux ② htons 漏写 ③ 内核没开 CONFIG_PACKET |
查 uname -s;补 htons;grep CONFIG_PACKET /boot/config-$(uname -r) |
ioctl SIOCGIFINDEX: No such device |
网卡名错了(比如写成 eth0 但实际是 ens33) |
ip -br link 确认真实名字 |
bind: No such device |
sll_ifindex 为 0 或没赋值 |
检查 ioctl 返回值有没有被忽略 |
| 收到 0 个包但程序在跑 | ① sll_protocol 没 htons ② 网卡确实没流量 ③ 走了错误的接口 |
ping 打一下;用 tcpdump -i <if> -c 3 交叉验证 |
| 包数量是 tcpdump 的两倍 | 没 bind(),收到所有接口 |
显式设 sll_ifindex |
| Ctrl-C 后统计没打印 | recv 的 EINTR 没判 |
if (errno == EINTR) continue; |
| 包长总是 1500 或 9000 整 | 网卡 GRO 聚合 | ethtool -K <if> gro off 关掉再测 |
setcap 后仍然 Permission denied |
文件系统不支持 xattr(如某些 NFS/overlay) | 换 sudo 跑,或把二进制放到正常 ext4 分区 |
六、验证清单
跑完这套流程,逐项打勾:
-
getcap ./mini_tcpdump能看到cap_net_raw,cap_net_admin=eip -
./mini_tcpdump lo能在ping 127.0.0.1时打印出 ICMP 报文 - 实验 1 里
len - iplen == 14 - 故意把网卡名写错,能看到
No such device而不是段错误 - 按 Ctrl-C,程序能打印
total N packets并正常退出(退出码 0) -
valgrind --leak-check=full ./mini_tcpdump lo无 definitely lost
七、这套代码离「生产级」还差什么
mini_tcpdump 已经能抓包了,但离 Suricata 的 source-af-packet.c 还差三个数量级:
- 它每次
recv都要一次系统调用 + 一次内存拷贝 。Suricata 用mmap+ 环形缓冲,把这两件事都省了 ------ 见 S02。 - 它没有分流能力 。单线程收包在 1Gbps 以上就会丢包。Suricata 用
PACKET_FANOUT把流量哈希到多个线程 ------ 见 S04。 - 它把解析逻辑写死在收包循环里 。Suricata 用
TmModule注册表把收包、解码、检测、输出拆成可插拔的槽位 ------ 见 S12。
下一篇我们就把第 1 点解决掉:把 recv 循环换成 mmap 环形缓冲,看性能能翻几倍。
下一篇 :TPACKET_V2 与 TPACKET_V3 环形缓冲对比:一块 mmap 内存如何撑起 10Gbps 收包