我想编写一个用于无线流量实时分析的工具。
有人知道如何在C语言中从混杂模式(或嗅探)设备读取数据吗?
我知道需要具有root权限才能这样做。我想知道是否有人知道必要的函数是什么。普通的套接字在这里似乎没有意义。
我想编写一个用于无线流量实时分析的工具。
有人知道如何在C语言中从混杂模式(或嗅探)设备读取数据吗?
我知道需要具有root权限才能这样做。我想知道是否有人知道必要的函数是什么。普通的套接字在这里似乎没有意义。
s = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL))
ldh = load halfword (from packet)
jeq = jump if equal
ret = return with exit code
ETH_P_ALL
是不够的;这是“SAP混杂”,因为您可以获取所有数据包而不考虑协议类型,但它不是“物理混杂”,因为适配器不会将未发送到主机的单播数据包传递给主机)。 - user862787我曾经需要监听原始以太网帧,最终创建了一个包装器。通过使用设备名称(例如eth0
)调用函数,我得到了一个处于混杂模式的套接字。
您需要做的是创建一个原始套接字,然后将其置于混杂模式。这是我的做法:
int raw_init (const char *device)
{
struct ifreq ifr;
int raw_socket;
memset (&ifr, 0, sizeof (struct ifreq));
/* Open A Raw Socket */
if ((raw_socket = socket (PF_PACKET, SOCK_RAW, htons (ETH_P_ALL))) < 1)
{
printf ("ERROR: Could not open socket, Got #?\n");
exit (1);
}
/* Set the device to use */
strcpy (ifr.ifr_name, device);
/* Get the current flags that the device might have */
if (ioctl (raw_socket, SIOCGIFFLAGS, &ifr) == -1)
{
perror ("Error: Could not retrive the flags from the device.\n");
exit (1);
}
/* Set the old flags plus the IFF_PROMISC flag */
ifr.ifr_flags |= IFF_PROMISC;
if (ioctl (raw_socket, SIOCSIFFLAGS, &ifr) == -1)
{
perror ("Error: Could not set flag IFF_PROMISC");
exit (1);
}
printf ("Entering promiscuous mode\n");
/* Configure the device */
if (ioctl (raw_socket, SIOCGIFINDEX, &ifr) < 0)
{
perror ("Error: Error getting the device index.\n");
exit (1);
}
return raw_socket;
}
在Linux上,WireShark具有捕获PLCP(物理层汇聚协议)头信息的能力。
为什么不使用类似WireShark这样的工具呢?
它是开源的,所以即使你不想直接使用它,至少你可以从中学到一些东西。