2015-04-06 41 views
1

我試圖使用pcap_dump()和pcap.h庫中的其他函數將示例數據包保存到.pcap文件。當我在Wireshark中打開它時,這些數字與我在程序中保存的數據不同。這裏是我的代碼:數據包在.pcap文件中存儲錯誤

void create_pcap_file() { 

string udp = "ff ff ff ff ff ff 00 21 85 11 29 1b 08 00 45 00 00 1c 0c 12 40 00 80 11 00 00 93 af 6a 8d ff ff ff ff 44 5c 44 5c 00 08 78 e9 "; 
u_char* packet = (u_char*)malloc(udp.size() * sizeof(u_char*)); 
for (int i = 0; i < udp.size(); i++) { 
    packet[i] = (u_char) udp[i]; 
} 

pcap_dumper_t * file = pcap_dump_open(pcap_open_dead(DLT_EN10MB, 65535), "dumper_item1.pcap"); 
pcap_pkthdr header; 
header.caplen = (bpf_u_int32)42; //size of an UDP/IP packet without any data 
header.len = (bpf_u_int32)42; 
header.ts.tv_sec = time(NULL); 
header.ts.tv_usec = 0; 
pcap_dump((u_char*)file, &header, packet); 
} 

Wireshark的顯示了這個: enter image description here

有誰知道爲什麼出現這種情況?

+1

你給它含有十六進制數字的字符串(0x66是「F」的代碼)。你可能打算給它字符串表示的字節序列。您需要將每對十六進制數字轉換爲一個無符號字符。 –

回答

3

正如艾倫斯托克斯在他的回答(他應該給出一個答案,而不僅僅是一個評論)中的註釋,pcap文件是二進制文件,而不是文本文件,所以內容應該是原始十六進制數據,而不是字符串看起來像十六進制數據轉儲的文本。

你想要的是:

void create_pcap_file() { 

u_char packet[] = { 
    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, // Ethernet destination address 
    0x00, 0x21, 0x85, 0x11, 0x29, 0x1b, // Ethernet source address 
    0x08, 0x00,       // Ethernet type (0x0800 = IPv4) 
    0x45,        // IPv4 version/IHL 
    0x00,        // IPv4 Type of Service 
    0x00, 0x1c,       // IPv4 total length (0x001c = 28) 
    0x0c, 0x12,       // IPv4 identification (0x0c12) 
    0x40, 0x00,       // IPv4 flags and fragment offset 
    0x80,        // IPv4 time-to-live (0x80 = 128) 
    0x11,        // IPv4 protocol (0x11 = 17 = UDP) 
    0x00, 0x00,       // IPv4 header checksum (not valid) 
    0x93, 0xaf, 0x6a, 0x8d,    // IPv4 source address (147.175.106.141) 
    0xff, 0xff, 0xff, 0xff,    // IPv4 destination address (255.255.255.255) 
    0x44, 0x5c,       // UDP source port (0x445C = 17500) 
    0x44, 0x5c,       // UDP destination port (0x445C = 17500) 
    0x00, 0x08,       // UDP length (0x0008 = 8) 
    0x78, 0xe9       // UDP checksum (0x78e9) 
}; 

pcap_dumper_t * file = pcap_dump_open(pcap_open_dead(DLT_EN10MB, 65535), "dumper_item1.pcap"); 
pcap_pkthdr header; 
header.caplen = (bpf_u_int32)sizeof packet; //size of an UDP/IP packet without any data 
header.len = (bpf_u_int32)sizeof packet; 
header.ts.tv_sec = time(NULL); 
header.ts.tv_usec = 0; 
pcap_dump((u_char*)file, &header, packet); 
} 
+0

是的,我沒有假設我保存的數字實際上是字符的ASCII值。問題解決了。 – witcher