在C++中读取pcap文件

4

我想读取pcap文件并获取流的数据包头信息...

为此,我找到了一个来自http://www.cnblogs.com/xiangshancuizhu/archive/2012/10/14/2723654.html的C++程序,该程序读取pcap文件并具有头指针,该指针仅指向头的长度,但是我想访问头的其他特性,比如syn、fin、ack、seq no等。下面是我的代码,请问如何实现?

 char errbuff[PCAP_ERRBUF_SIZE];

/*
* Step 4 - Open the file and store result in pointer to pcap_t
*/

// Use pcap_open_offline
// http://www.winpcap.org/docs/docs_41b5/html/group__wpcapfunc.html#g91078168a13de8848df2b7b83d1f5b69
pcap_t * pcap = pcap_open_offline(file.c_str(), errbuff);

/*
* Step 5 - Create a header and a data object
*/

// Create a header object:
// http://www.winpcap.org/docs/docs_40_2/html/structpcap__pkthdr.html
struct pcap_pkthdr *header;

// Create a character array using a u_char
// u_char is defined here:
// C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Include\WinSock2.h
// typedef unsigned char   u_char;
const u_char *data;

/*
* Step 6 - Loop through packets and print them to screen
*/
u_int packetCount = 0;
while (int returnValue = pcap_next_ex(pcap, &header, &data) >= 0)
{
    // Print using printf. See printf reference:
    // http://www.cplusplus.com/reference/clibrary/cstdio/printf/

    // Show the packet number
    printf("Packet # %i\n", ++packetCount);

    // Show the size in bytes of the packet
    printf("Packet size: %d bytes\n", header->len);

头部(header)是一个像这样的结构:

struct pcap_pkthdr {
    struct timeval ts;  /* time stamp */
    bpf_u_int32 caplen; /* length of portion present */
    bpf_u_int32 len;    /* length this packet (off wire) */
};

我希望这个结构有更多的成员,我该怎么做? 非常感谢。
2个回答

4

您不能向pcap_pkthdr添加更多字段- libpcap不会对这些字段采取任何措施。如链路层、IP和TCP头等数据包数据字段,不是该头部的特征。

数据包数据由data变量指向。那里是链路层头部,在IP数据包中是IP头,在TCP数据包中是TCP头,依此类推。例如,请参见Tim Carstens关于如何使用libpcap的教程

您可能希望考虑使用libcrafter构建程序,它是“用于C ++的高级库,旨在更轻松地创建和解码网络数据包”。您可能对“解码”部分感兴趣,而不是“制作”部分。


非常感谢您的回答,我已经阅读了这个库,正如我所说,我想要访问标志位。从这个库函数中我可以得到标志位,输出结果如下: < TCP (20 bytes) :: SrcPort = 0 , DstPort = 80 , SeqNumber = 0 , AckNumber = 0 , DataOffset = 5 , Reserved = 0 , Flags = ( ) , WindowsSize = 5840 , CheckSum = 0x0 , UrgPointer = 0 , > 但是我该如何使用这些标志位,并找到TCP数据包中的SIN或FIN呢? - m.eslampnah

0

如果你想读取一个pcap文件(不使用任何外部库来读取pcap文件),你需要按照以下格式解析该文件

全局头|数据包头|数据包数据|数据包头|数据包数据|....

先读取全局头,然后在一个循环中解析数据,直到文件结束。 你必须知道正确的格式,且你的结构必须正确。

为此,你可以参考这个链接 https://www.tcpdump.org/pcap.html **该链接中未提到UDP头


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接