在 C 语言的 linux 上,设置接口 PROMISC 并使用原始套接字后,我可以通过 read() 读取接口上的传入数据包。
但是,它不会获取所有数据包。在从文件描述符读取下一个可用数据之前,Read() 会阻塞“长时间”(<1s,但数据包以每秒数百个速度流动)。
一定有什么遗漏或根本错误。
“使用 libpcap”不是有效的答案。我查看了他们的代码,找不到区别(libpcap 不会丢失数据包)
初始化 fd:
if ((fd = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL))) < 0) {
perror("socket(PF_PACKET) failed");
return 1;
}
memset(&ifr, 0, sizeof(ifr));
strncpy(ifr.ifr_name, iface, sizeof(ifr.ifr_name) - 1);
if (ioctl(fd, SIOCGIFINDEX, &ifr) < 0) {
perror("ioctl(SIOCGIFINDEX) failed");
return 1;
}
memset(&sll, 0, sizeof(sll));
sll.sll_family = AF_PACKET;
sll.sll_ifindex = ifr.ifr_ifindex;
sll.sll_protocol = htons(ETH_P_ALL);
if ((ifr.ifr_flags | IFF_UP | IFF_BROADCAST | IFF_RUNNING) != ifr.ifr_flags) {
ifr.ifr_flags |= IFF_UP | IFF_BROADCAST | IFF_RUNNING;
if( ioctl( fd, SIOCSIFFLAGS, &ifr ) < 0 ) {
perror("ioctl(SIOCSIFFLAGS) failed");
return 1;
}
}
if (bind(fd, (struct sockaddr *) &sll, sizeof(sll)) < 0) {
perror("bind(ETH_P_ALL) failed");
return 1;
}
if (ioctl(fd, SIOCGIFHWADDR, &ifr) < 0)
{
perror("ioctl(SIOCGIFHWADDR) failed");
return 1;
}
if (ifr.ifr_hwaddr.sa_family != ARPHRD_IEEE80211 &&
ifr.ifr_hwaddr.sa_family != ARPHRD_IEEE80211_PRISM &&
ifr.ifr_hwaddr.sa_family != ARPHRD_IEEE80211_FULL)
{
if (ifr.ifr_hwaddr.sa_family == 1)
fprintf(stderr, "\nARP linktype is set to 1 (Ethernet) ");
else
fprintf(stderr, "\nUnsupported hardware link type %4d ",
ifr.ifr_hwaddr.sa_family);
fprintf(stderr, "- expected ARPHRD_IEEE80211,\nARPHRD_IEEE80211_"
"FULL or ARPHRD_IEEE80211_PRISM instead. Make\n"
"sure RFMON is enabled: run 'airmon-ng start %s"
" <#>'\nSysfs injection support was not found "
"either.\n\n", iface);
return 1;
}
memset(&mr, 0, sizeof(mr));
mr.mr_ifindex = sll.sll_ifindex;
mr.mr_type = PACKET_MR_PROMISC;
if (setsockopt(fd, SOL_PACKET, PACKET_ADD_MEMBERSHIP, &mr, sizeof(mr)) < 0) {
perror("setsockop(PACKET_MR_PROMISC) failed");
return 1;
}
读:
while (caplen > 0) {
if ((caplen = read(fd, p, read_size)) < 0) {
perror("read failed");
break;
}
p += caplen;
read_size -= caplen;
}
}