2012-11-07 42 views
0

我已經寫了一個pcap程序,它使用pcap_open_live()並逐步應用過濾器(即重新編譯pcap過濾器並在初始pcap_loop之後再次設置過濾器),並且我想在我已保存的某些pcap文件上測試它從Wiresharkpcap_set_filter()與pcap_open_offline()一起工作嗎?

但是,當我運行該程序時,我甚至無法打印出我的數據包,除非我向pcap_compile_filter提供一個空過濾器;

這只是在保存的文件上使用lpcap的功能,還是我做錯了什麼?

下面的代碼爲細讀一個片段:

int main(int argc, char **argv) 
{ 
char *dev = NULL;   /* capture device name */ 
char errbuf[PCAP_ERRBUF_SIZE];  /* error buffer */ 
pcap_t *handle;    /* packet capture handle */ 
char filter_exp[] = "ip";   /* filter expression [3] */ 
struct bpf_program fp;   /* compiled filter program (expression) */ 
bpf_u_int32 mask;   /* subnet mask */ 
bpf_u_int32 net;   /* ip */ 
int num_packets = -1;   /* number of packets to capture -1 => capture forever! */ 

printf("Filter expression: %s\n", filter_exp); 

// open capture device 
handle = pcap_open_offline("heartbeats2", errbuf); 
if (handle == NULL) { 
    fprintf(stderr, "pcap_open_offline failed: %s\n", errbuf); 
    exit(EXIT_FAILURE); 
} 

/* make sure we're capturing on an Ethernet device*/ 
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, 0) == -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_loop(handle, -1, gotPacket, NULL); 

pcap_freecode(&fp); 
pcap_close(handle); 

printf("\nCapture complete.\n"); 

return(0); 
} 

的有包函數只是打印出數據包的有效載荷;輸出只是:

Filter expression: ip 

Capture complete. 
+1

@nos數據包上沒有vlan,我把以太網報頭大小設置爲14.協議棧是ethernet,ip,udp,用於我感興趣的數據包。 – Eosis

+0

嗯,我在Mountain Lion上試了它一個捕獲文件,還有一個'gotPacket'函數,它打印出「Got a packet」。如果我從'pcap_compile()'和'pcap_setfilter()'調用'#if 0',它會報告文件中每個數據包的「Got a packet」如果我刪除'#if 0'和'#endif',它會爲文件中的每個IP數據包報告「有一個數據包」。但是,請注意'''ip「表示IPv4,* NOT * IPv6 - 您需要ip6用於IPv6。 – 2012-11-09 18:46:04

回答

0

沒有看到你的gotPacket函數,不可能說出那裏發生了什麼。

由於沒有其他錯誤消息,程序運行到代碼末尾並打印「Capture complete」。信息。

如果您的程序使用pcap_open_live()和空濾鏡,我會懷疑您的pcap文件可能不包含任何ip數據包。

您可以使用wireshark打開您的pcap文件,並在wireshark過濾器表達式中使用「ip」過濾器。如果你可以在wireshark中看到一些數據包,那麼你的上面的程序也應該使用過濾器。

有很多網站有BPF的例子。一個示例網站可能是http://biot.com/capstats/bpf.html

相關問題