#read-write #pcap #read #write #pcap-parser #parse #parser

legacy_pcap_file

一个用于读取和写入旧版 Pcap 文件格式的 crate

1 个不稳定版本

0.1.0 2022年11月22日

#2886解析器实现

MIT/Apache

54KB
1.5K SLoC

旧版 Pcap 解析与写入

GitHub Workflow Status

这是 courvoif/pcap-file 的修改版,只支持旧的旧版 pcap 文件格式(.pcap 扩展名)。

PCAP 格式非常简单。有关其结构的描述,请参见此处。此 crate 提供了一些抽象,用于读取和写入,包括流变体。它也是非异步的。

此 crate 没有外部依赖(除了 std)。它也没有不安全代码。

所有抽象都使用标准库的 ReadWrite 特性。

示例

以简单的方式读取数据

    use legacy_pcap_file::PcapReader;

    // Let's assume this is some pcap data. It can also be a file.
    // Anything implementing `Read`.
    let some_buffer = vec![];
    let pcap_reader = PcapReader::new(&some_buffer).unwrap();

    // Packets can be iterated on.
    for res in pcap_reader {
        // For each packet we get a result, since there are a few errors that
        // can pop up:
        // * The data source can be exhausted mid packet.
        // * The packet header length may be shorter than actual data length. 
        let pkt = res.unwrap();
        // Use the packet.
        ...
    }

在重用数据包缓冲区的同时读取数据。(这有点像黑客技巧)。

    use legacy_pcap_file::PcapReader;

    // Let's assume this is some pcap data. It can also be a file.
    // Anything implementing `Read`.
    let some_buffer = vec![];
    let pcap_reader = PcapReader::new(&some_buffer).unwrap();

    // Define some backing data for the packets payload.
    let mut backing_data = vec![]; 
    // Iterate manually.
    while let Some(Ok(pkt)) = pcap_reader.next_with(backing_data) {
        // here you can use the packet, clone it, etc..
        ...
        // reuse the data.
        backing_data = pkt.data;
    }

写入数据

    use legacy_pcap_file::{PcapHeader, PcapPacket, PcapFileWriter};

    // Let's say you have a pcap header defined
    let header: PcapHeader = ...
    // and some supply of packets
    let packets: Vec<PcapPacket> = ...
    // They can be written like so
    let path = Path::from("/some/file/path");
    let mut pcap_file_writer = PcapFileWriter::new_with_header(&path, header).unwrap();
    for packet in packets {
        // Some errors that can occur:
        // * The backing storage maybe error in some way (IO error).
        // * The packets are not well formed (mostly declared payload length 
        //   does not match real length).
        pcap_file_writer.write_packet(&packet).unwrap();
    }
    pcap_file_writer.close().unwrap();

许可证

许可协议为 MIT/Apache-2.0。

无运行时依赖