如何使用libpcap嗅探多个设备?

时间:2010-10-14 01:42:25

标签: libpcap

我正在尝试创建一个可以在多个设备上嗅探的嗅探器。在我的代码中,程序将收到用户想要嗅探的设备列表。我获取设备列表并将其存储到我用来循环的数组中并传递给创建pcap_t句柄的函数,如下面的函数所示:

void *startPcapProcess(char * dev){
    char errbuf[PCAP_ERRBUF_SIZE];     /* error buffer */
    pcap_t *handle;                    /* packet capture handle  */

/* filter expression [3] */
char filter_exp[] = "(dst port 53) and (udp[0xa] & 0x78 = 0x28)"; 

struct bpf_program fp;      /* compiled filter program (expression) */
bpf_u_int32 mask;           /* subnet mask */
bpf_u_int32 net;            /* ip */

printf("%s","startPacketProcess called\n");
printf("Device sent to startPacketProcess: %s\n", dev);
/* get network number and mask associated with capture device */
if (pcap_lookupnet(dev, &net, &mask, errbuf) == -1) {
    fprintf(stderr, "Couldn't get netmask for device %s: %s\n",
            dev, errbuf);
    net = 0;
    mask = 0;
}

/* open capture device */
handle = pcap_open_live(dev, SNAP_LEN, 1, 1000, errbuf);
if (handle == NULL) {
    fprintf(stderr, "Couldn't open device %s: %s\n", dev, errbuf);
    exit(EXIT_FAILURE);
}

/* make sure we're capturing on an Ethernet device [2] */
if (pcap_datalink(handle) != DLT_EN10MB) {
    fprintf(stderr, "%s is not an Ethernet\n", dev);
    exit(EXIT_FAILURE);
}

/* compile the filter expression */
if (pcap_compile(handle, &fp, filter_exp, 0, net) == -1) {
    fprintf(stderr, "Couldn't parse filter %s: %s\n",
        filter_exp, pcap_geterr(handle));
    exit(EXIT_FAILURE);
}

/* apply the compiled filter */
if (pcap_setfilter(handle, &fp) == -1) {
    fprintf(stderr, "Couldn't install filter %s: %s\n",
        filter_exp, pcap_geterr(handle));
    exit(EXIT_FAILURE);
}

pcap_freecode(&fp);

/* now we can set our callback function */
pcap_loop(handle, -1, process_packet, NULL);
printf("%s","End startPacketProcess call\n");

}

但是,当我在for循环中调用此函数时,它只能在一个设备上捕获,因为它似乎卡在了pcap_loop回调函数中。因此我尝试做多线程和for循环,我用来传递所有设备打开和捕获循环,但pcap_loop回调函数似乎没有执行。以下代码显示了我对多线程的使用:

for (i = 0; i < numDevice; i++){
        printf("Device returned by getDevices call: %s\n", deviceList[i]);
        printf("%s","Entering for loop\n");
        pthread_create(&tid, thAttr, startPacketProcess,(void*)deviceList[i]);
    }

有谁知道我做错了什么,你能否就如何解决这个问题向我提出建议?

谢谢, 灵

2 个答案:

答案 0 :(得分:1)

process_packet可能是问题所在。尝试在线程上下文中获取数据包。

  struct pcap_pkthdr *pkt_header;   
  u_char *pkt_data;         

  while ((retval = pcap_next_ex(mpPcap, &pkt_header, (const u_char **) &pkt_data)) >= 0)   {
    //Do Whatever
  } 

答案 1 :(得分:0)

您是否尝试过使用pcap_findalldevs()pcap_findalldevs_ex()