【问题标题】:How to write PCAP capture file header?如何编写 PCAP 捕获文件头?
【发布时间】:2011-07-11 09:13:06
【问题描述】:

在不使用 libpcap 的情况下,我正在尝试编写一个遵循 pcap 文件格式 (format) 的日志文件。这个文件需要被 WireShark 读取。到目前为止,我已经用 C++ 编写了这个:

struct pcapFileHeader {
    uint32_t magic_number;   /* magic number */
    uint16_t version_major;  /* major version number */
    uint16_t version_minor;  /* minor version number */
    int16_t  thiszone;       /* GMT to local correction */
    uint32_t sigfigs;        /* accuracy of timestamps */
    uint32_t snaplen;        /* max length of captured packets, in octets */
    uint32_t network;        /* data link type */
};

ofstream fileout;
fileout.open("file.pcap", ios::trunc);

pcapFileHeader fileHeader;
fileHeader.magic_number = 0xa1b2c3d4;
fileHeader.version_major = 2;
fileHeader.version_minor = 4;
fileHeader.thiszone = 0;
fileHeader.sigfigs = 0;
fileHeader.snaplen = 65535; //(2^16)
fileHeader.network = 1;     //Ethernet

fileout <<  fileHeader.magic_number <<
            fileHeader.version_major <<
            fileHeader.version_minor <<
            fileHeader.thiszone <<
            fileHeader.sigfigs <<
            fileHeader.snaplen <<
            fileHeader.network;

fileout.close();

所以这个应该制作一个空白的捕获文件,但是当我在 Wireshark 中打开它时,我会看到:

文件“hello.pcap”似乎在数据包或其他数据的中间被缩短了。

我尝试以二进制模式打开输出文件,但没有帮助。我会在 WireShark 论坛上发布这个,但我认为这是用户错误,而不是 WireShark 的问题。

我们将不胜感激。

【问题讨论】:

    标签: c++ logging wireshark pcap libpcap


    【解决方案1】:

    &lt;&lt; 写入格式化为文本的数字(例如,五个字符的字符串“65535”而不是代表该数字的四个字节)。

    要输出二进制数据,请使用ios::binary 打开文件并使用write。这条语句会写出整个头部:

    fileout.write(reinterpret_cast<const char*>(&fileHeader),
                  sizeof fileHeader);
    

    读取器检测到字节序,因此只要结构成员之间没有填充,它就可以移植。

    注意thiszone 应该是int32_t

    【讨论】:

    • 如果操作在重要的系统上,也可以使用ios::binary 打开文件
    猜你喜欢
    • 2012-06-23
    • 2016-02-04
    • 2012-06-24
    • 1970-01-01
    • 1970-01-01
    • 2010-10-15
    • 2015-09-18
    • 2014-04-09
    • 1970-01-01
    相关资源
    最近更新 更多