我正在努力将原始套接字绑定到接口,我的目标是实现简单的数据包嗅探器。
已经花费了数小时在网上搜索并查阅了一些参考资料,其中一部分列在底部。
我能够打开套接字,在bind时没有错误,但在剥离以太网头并观察IP头时,我发现捕获了回环(127.0.0.1)和其他不需要的ethX接口流量。
结论之一是在我的情况下不能使用setsockopt,以下是我的代码片段:
Thanks in advance!
参考资料:
我能够打开套接字,在bind时没有错误,但在剥离以太网头并观察IP头时,我发现捕获了回环(127.0.0.1)和其他不需要的ethX接口流量。
结论之一是在我的情况下不能使用setsockopt,以下是我的代码片段:
struct sockaddr_ll sll;
int raw_sock;
raw_sock = socket( PF_PACKET , SOCK_RAW , htons(ETH_P_ALL)) ;
// also tried with AF_PACKET
bzero(&sll , sizeof(sll));
sll.sll_family = PF_PACKET;
// also tried with AF_PACKET
sll.sll_ifindex =get_iface_index(raw_sock,"eth1");
// returns valid ifr.ifr_ifindex;
sll.sll_protocol = htons(ETH_P_ALL);
if((bind(raw_sock , (struct sockaddr *)&sll , sizeof(sll))) ==-1)
{
perror("bind: ");
exit(-1);
}
saddr_size = (sizeof sll);
data_size = recvfrom(raw_sock , buffer_ptr, 65536, 0 , &sll , (socklen_t*)&saddr_size);
Thanks in advance!
参考资料:
- http://man7.org/linux/man-pages/man7/packet.7.html
- http://man7.org/linux/man-pages/man2/bind.2.html
- 在 Fedora core 6(2.6.18-1.2798.fc6) 中使用 setsockopt() 系统绑定设备的原始套接字无法工作
- 如何将原始套接字绑定到特定接口
编辑-1: 非常感谢您抽出时间回复,我在无休止的寻找解决方案中感到迷茫和沮丧。
- I'm restricted to my own implementation, thus unable to use libcap nor others.
Interface index returned from ioctl call SIOCGIFINDEX is 3 in my case and is identical to sll.sll_ifindex value. Assuming I can rely on "ip link show" - my eth1 index is indeed 3.
int get_iface_index(int socket,char *iface_name){ struct ifreq ifr; char ifname[IFNAMSIZ]="eth1"; // Ugly hard coded, will be changed memset(&ifr, 0, sizeof(struct ifreq)); strncpy((char *)ifr.ifr_name, ifname, IFNAMSIZ); if (ioctl(socket, SIOCGIFINDEX, &ifr) < 0){ perror("ioctl: "); return -1; } return ifr.ifr_ifindex; // Always success here 2 for eth0, 3 for eth1 }
strace(1)
来调查你传递给ioctl(2)
和bind(2)
系统调用的参数。 - nodakai