#networking #packet #capture #pcap #sniffing

wiretap

Basic packet capture library built on parallelism

8 releases (5 breaking)

new 0.6.0 Dec 13, 2024
0.5.0 Aug 4, 2024
0.4.0 Sep 12, 2023
0.3.2 Sep 11, 2023
0.1.0 May 27, 2023

#1569 in Network programming

Download history 5/week @ 2024-09-13 17/week @ 2024-09-20 19/week @ 2024-09-27 4/week @ 2024-10-04

501 downloads per month

MIT license

20KB
387 lines

wiretap


lib.rs:

wiretap

wiretap wraps lower level networking and concurency libraries to make packet capture easier in Rust programs

Examples

Capture-then-process

This basic example shows how to capture packets and later do something with the TCP ones

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());
}

Process-while-capturing

This basic example shows how to process packets with a callback as they are captured

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();
}

Dependencies

~4–5.5MB
~103K SLoC