2011-10-27 31 views
3

为了使用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 
    read data from every ready file descriptor using pcap_dispatch() 
    handle EndOfStream or Errors and break out of loop if needed 

难道这还不够,还是有一些特别的注意事项采取考虑到?

回答

3

多个接口的注意事项和方法嗅探很好解释here

1

我遇到了一些问题,试图从与pcap的特定接口捕获并在此处询问。似乎很少有人熟悉pcap。我的问题和答案,我终于得到了指出很有帮助的详细信息,可以在这里找到在下面的链接,你可能会发现有用:

Confused by libcap (pcap) and wireless

+0

这并没有解决从一组特定的接口同时嗅探,而是选择()(你提到)应像往常一样处理。 – gnometorule

+0

感谢您指出这些额外的信息。 – ziu

-1

要从多个网络接口捕获数据包,您需要先呼叫fork()新子进程,然后执行pcap_lookupnet(),然后执行pcap_open_live()

注意:您不能使用线程代替为每个网络接口创建子进程。

3
#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 file.c -lpcap

./file的eth0 eth1的为wlan0