我已經寫了一個pcap
程序,它使用pcap_open_live()
並逐步應用過濾器(即重新編譯pcap
過濾器並在初始pcap_loop之後再次設置過濾器),並且我想在我已保存的某些pcap
文件上測試它從Wireshark
。pcap_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.
@nos數據包上沒有vlan,我把以太網報頭大小設置爲14.協議棧是ethernet,ip,udp,用於我感興趣的數據包。 – Eosis
嗯,我在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