2016-04-27 70 views
0

我想读取pcap文件像一些数据结构像矢量或数组,然后在应用程序中使用收集的数据(只有选择一个像包长度,时间戳)。我发现了一些示例应用程序读取PCAP:阅读pcap文件向量/数组

#include <stdio.h> 
#include <pcap.h> 

#define LINE_LEN 16 

void dispatcher_handler(u_char *, const struct pcap_pkthdr *, const u_char *); 

int main(int argc, char **argv) 
{ 
    pcap_t *fp; 
    char errbuf[PCAP_ERRBUF_SIZE]; 

    if(argc != 2) 
    { 
     printf("usage: %s filename", argv[0]); 
     return -1; 

    } 

    /* Open the capture file */ 
    if ((fp = pcap_open_offline(argv[1],   // name of the device 
         errbuf     // error buffer 
         )) == NULL) 
    { 
     fprintf(stderr,"\nUnable to open the file %s.\n", argv[1]); 
     return -1; 
    } 

    /* read and dispatch packets until EOF is reached */ 
    pcap_loop(fp, 0, dispatcher_handler, NULL); 

    pcap_close(fp); 
    return 0; 
} 



void dispatcher_handler(u_char *temp1, 
         const struct pcap_pkthdr *header, 
         const u_char *pkt_data) 
{ 
    u_int i=0; 

    /* 
    * unused variable 
    */ 
    (VOID*)temp1; 

    /* print pkt timestamp and pkt len */ 
    printf("%ld:%ld (%ld)\n", header->ts.tv_sec, header->ts.tv_usec, header->len); 

    printf("\n\n"); 

} 

问题是与pcap_loop()。我找到了documentation,但唯一的信息是,这是读取整个文件,直到文件结束。我一直试图将文件视为典型的FILE,并在while循环中读取,直到EOF,但它不起作用,因为我不能简单地将fp视为FILE

此外,我没有看到任何可能性将指针传递给pcap_handler以稍后检索它。

有人可以建议我怎么能做到这一点吗?

回答

0

我经过进一步的文档和互联网调查我发现功能:pcap_next_ex()

感谢,我现在可以使用while循环和阅读逐行(或包更精确地包)。总的想法是:

struct pcap_pkthdr *header; 
const u_char *pkt_data; 
int res; 

while((res = pcap_next_ex(fp, &header, &pkt_data)) >= 0) 
{ 
    //Process packet 
} 
0

根据文档,您的代码看起来不错。 pcap_loop应该做文件阅读,你不应该试着去做。

文档提到的一件事是,在旧的pcap版本中,对于pcap_loop中的count为0是未定义的,因此在连接到较旧版本的情况下使用-1应该更安全。

0

我一直在试图把文件作为一个典型的FILE,并在while循环读取直到EOF,但它不工作,因为我不能简单地把fpFILE

没有,因为它不是一个FILE。 (您还可以从pcap_open_live()或从pcap_create()/pcap_activate()组合pcap_t *,但给你一个手柄,实时捕捉,而不是一个文件。)

此外,我看不出有任何的可能性来传递指针到pcap_handler稍后检索它。

第四个参数pcap_loop()作为第一个参数传递给pcap_handler,所以你可以做

pcap_loop(fp, 0, dispatcher_handler, pointer); 

,然后在dispatcher_handler(),投temp1为适当的类型和使用它 - 将指向pointer所做的一样。