如何使用pcap从多个接口捕获流量

如何使用pcap从多个接口捕获流量,c,linux,interface,pcap,C,Linux,Interface,Pcap,为了使用pcap从多个接口进行嗅探,我将在伪代码中执行以下操作: foreach interface: open a file descriptor using pcap_open_live() set the file descriptor to non-blocking while true: check for a ready file descriptor using select() or an equivalent I/O multiplexer r

为了使用pcap从多个接口进行嗅探,我将在伪代码中执行以下操作:

foreach interface:
    open a file descriptor using pcap_open_live()
    set the file descriptor to non-blocking

while true:
    check for a ready file descriptor using select() or an equivalent I/O multiplexer
    read data from every ready file descriptor using pcap_dispatch()
    handle EndOfStream or Errors and break out of loop if needed

这是否足够,或者是否有一些特别的注意事项需要考虑?

我在尝试从pcap的特定接口捕获数据时遇到了一些问题,并在这里询问了这些问题。似乎很少有人熟悉pcap。我的问题,以及我最后得到的一个答案,指出了非常有用的细节,可以在下面的链接中找到,您可能会发现它很有用:


要从多个网络接口捕获数据包,您需要调用fork新的子进程,然后执行pcap\u lookupnet,然后执行pcap\u open\u live


注意:不能使用线程而不是为每个网络接口创建子进程

下面是一个小的C程序片段,它使用PCAP库在网络中以promiscus隐形模式捕获嗅探网络数据包

#include <stdio.h>
#include <stdlib.h>
#include <pcap.h>  /* GIMME a libpcap plz! */
#include <errno.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>  

void callback(u_char *useless,const struct pcap_pkthdr* pkthdr,const u_char* packet)
{
  static int count = 1;
  printf("\nPacket number [%d], length of this packet is: %d\n", count++, pkthdr->len);
}

void pktinit(char *dev) /*function: for individual interface packet capturing*/
{
    char errbuf[PCAP_ERRBUF_SIZE];
    pcap_t* descr;
    struct bpf_program fp;        /* to hold compiled program */
    bpf_u_int32 pMask;            /* subnet mask */
    bpf_u_int32 pNet;             /* ip address*/
    pcap_if_t *alldevs, *d;
    char dev_buff[64] = {0};
    int i =0;
    pcap_lookupnet(dev, &pNet, &pMask, errbuf);
    descr = pcap_open_live(dev, BUFSIZ, 0,-1, errbuf);
    if(descr == NULL)
    {
        printf("pcap_open_live() failed due to [%s]\n", errbuf);
        return -1;
    }
    return 0;
}

int main(int argc, char **argv)
{
    int pid,i;
    if(argc < 2) /*command <eth0> [eth1]...*/
    {
        fprintf(strerr,"command needs ethernet name")
        return 0;
    }
    for(i = 1; i < argc; i++)
    {
        if((pid=fork()) != -1)
        {
            pktinit(argv[i])
        }
        else
        {
            fprintf(stderr,"pacp failed for: %s\n", argv[i]);
        }
    }
    return 0;
}
gcc文件.c-lpcap /文件eth0 eth1 wlan0手册页,共页,内容如下:

pcap_open_live用于获取要查看的数据包捕获句柄 网络上的数据包。设备是指定网络的字符串 开启装置;在内核为2.2或更高版本的Linux系统上,设备 参数any或NULL可用于从所有 接口

答案在最后一行


因此,请在pcap\u open\u live call的设备参数中使用any或NULL来捕获所有接口。

这并不能解决从某一组接口同时进行嗅探的问题,但如您所述的选择应该像往常一样处理该问题。