1

我正在尝试创建一个可以在多个设备上嗅探的嗅探器。在我的代码中,程序将接收用户想要嗅探的设备列表。我获取设备列表并将其存储到一个数组中,该数组用于循环并传递给创建 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]);
    }

有谁知道我做错了什么,你能为我提供如何解决这个问题的建议吗?

谢谢,林

4

2 回答 2

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
  } 
于 2011-08-23T02:19:52.277 回答
0

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

于 2011-02-03T11:59:41.583 回答