2016-04-27 44 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所做的一樣。