我尝试使用原始套接字捕获端口镜像数据包(跳过错误检查以仅显示主代码):
int sock = socket(AF_PACKET, SOCK_RAW, htons(ETH_P_ALL));
int size = recvfrom(sock, buf, 65536, 0, &saddr, &saddr_size);
struct iphdr* iph = (struct iphdr*)(buf + sizeof(struct ethhdr));
if (iph->protocol != 6 || iph->saddr != inet_addr("192.168.12.48")) return;
printf("got it\n");
虽然tcpdump可以捕获数据包,但我的程序不能。这是一个数据包的转储:
22:19:42.140498 IP (tos 0x0, ttl 54, id 42987, offset 0, flags [DF], proto TCP (6), length 52)
192.168.12.48.33011 > 172.16.103.12.57102: Flags [.], cksum 0xf4ef (correct), ack 7, win 186, options [nop,nop,TS val 1950796524 ecr 3768292988], length 0
0x0000: 4500 0034 a7eb 4000 3606 bce3 c0a8 0c30 E..4..@.6......0
0x0010: ac10 670c 80f3 df0e 983d f043 d1c7 3087 ..g......=.C..0.
0x0020: 8010 00ba f4ef 0000 0101 080a 7446 caec ............tF..
0x0030: e09b 967c ...|
我使用的是CentOS 6.5内核2.6.32-431.29.2.el6.x86_64。我已经禁用了防火墙并将rp_filter设置为0.有谁知道如何在C中捕获此类数据包?