#capture #packet #networking #pcap #sniffing

wiretap

基于并行构建的基本数据包捕获库

7 个版本 (4 个破坏性版本)

0.5.0 2024 年 8 月 4 日
0.4.0 2023 年 9 月 12 日
0.3.2 2023 年 9 月 11 日
0.3.1 2023 年 8 月 30 日
0.1.0 2023 年 5 月 27 日

#1414 in 网络编程

Download history 49/week @ 2024-04-23 91/week @ 2024-07-30 34/week @ 2024-08-06

每月 125 次下载

MIT 许可证

20KB
384

wiretap


lib.rs:

wiretap

wiretap 将底层网络和并发库包装起来,以简化 Rust 程序中的数据包捕获

示例

捕获后处理

此基本示例展示了如何捕获数据包并在之后对 TCP 数据包进行处理

use wiretap;
use std::{thread, time};

fn main() {
    // Create a new PacketCapture with the "lo" interface
    let pc = wiretap::PacketCapture::new_from_interface("lo").unwrap();
    // Start a capture on that interface
    let pc = pc.start_capture();
    // Do something useful, probably
    thread::sleep(time::Duration::from_secs(15));
    // Stop the capture
    let pc = pc.stop_capture();
    // Get the resulting TCP packets
    let output = pc.results_as_tcp();
    // Do something with them
    println!("Captured {} TCP packets", output.len());
    for out in output.iter() {
        println!("{:?}", out.payload());
}

捕获时处理

此基本示例展示了如何捕获数据包时使用回调进行处理

use wiretap;
use std::{thread, time};

// Print the SrcIP:SrcPort --> DestIP:DestPort
fn print_to_from(bytes: Vec<u8>) {
    // Make sure the payload represents an EthernetPacket
    if let Some(ethernet_packet) = wiretap::EthernetPacket::new(&bytes) {
        // Make sure the EthernetPacket payload represents an Ipv4Packet
        if let Some(ipv4_packet) = Ipv4Packet::new(ethernet_packet.payload()) {
            // Make sure the Ipv4Packet payload represents an TcpPacket
            if let Some(tcp_packet) = TcpPacket::new(ipv4_packet.payload()) {
                // Print out the interesting information
                println!("Packet: {}:{} --> {}:{}", ipv4_packet.get_source(), tcp_packet.get_source(), ipv4_packet.get_destination(), tcp_packet.get_destination() )
            }
        }
    }
}

fn main() {
    // Create a new PacketCapture with the default interface
    let pc = wiretap::PacketCapture::new_with_default().unwrap();
    // Start a capture on that interface
    let pc = pc.start_live_process(print_to_from);
    // Stuff happens
    thread::sleep(time::Duration::from_secs(15));
    // Stop the capture
    started.stop_capture();
}

依赖项

~4–5.5MB
~104K SLoC