### Perform a Quick Device Capture in Rust Source: https://github.com/rust-pcap/pcap/blob/main/_autodocs/api-reference/device.md Opens a network device for capturing packets and processes the first 10 packets received. This example uses `Device::lookup()` to find a device and `device.open()` to start capturing. ```rust use pcap::Device; fn main() -> Result<(), Box> { let device = Device::lookup()? .expect("No device found"); let mut capture = device.open()?; for _ in 0..10 { match capture.next_packet() { Ok(packet) => println!("Packet received: {} bytes", packet.len()), Err(e) => println!("Error: {}", e), } } Ok(()) } ``` -------------------------------- ### Method Documentation Example Source: https://github.com/rust-pcap/pcap/blob/main/_autodocs/INDEX.md Illustrates the standard format for documenting Rust methods, including signature, description, parameters, return values, and a runnable code example. ```Rust ```rust fn capture_packets(interface: &str, filter: &str) -> Result, Error> { // ... implementation ... } ``` **Parameters:** | Name | Type | Required | Default | Description | |-----------|---------|----------|---------|---------------------------------| | interface | &str | Yes | None | The network interface to capture on | | filter | &str | No | "" | BPF filter string to apply | **Returns:** - `Ok(Vec)`: A vector of captured packets if successful. - `Err(Error)`: An error if the capture fails. ``` ```Rust ```rust // Example usage: let packets = capture_packets("eth0", "tcp port 80").expect("Failed to capture packets"); for packet in packets { println!("Captured packet: {:?}", packet.header); } ``` ``` -------------------------------- ### Install LLVM Coverage Tools Source: https://github.com/rust-pcap/pcap/blob/main/CONTRIBUTING.md Installs the `llvm-tools-preview` component for nightly Rust, which is required for LLVM code coverage. ```bash rustup component add llvm-tools-preview ``` -------------------------------- ### Error Documentation Example Source: https://github.com/rust-pcap/pcap/blob/main/_autodocs/INDEX.md Demonstrates the standard format for documenting Rust error types, including variant, trigger conditions, root causes, handling examples, and notes. ```Rust ```rust Error::PermissionDenied ``` **Trigger Conditions:** | Condition | Context | |-------------------------------|---------------------------------------| | Attempting to capture on a | Requires root/administrator privileges | | privileged interface without | | | sufficient permissions. | | **Root Causes:** - Running the capture process as a non-privileged user. **Handling:** ```rust match capture_packets("eth0", "") { Ok(packets) => println!("Captured {} packets.", packets.len()), Err(Error::PermissionDenied) => eprintln!("Error: Permission denied. Please run as root."), Err(e) => eprintln!("An unexpected error occurred: {}", e), } ``` ``` -------------------------------- ### Install grcov Source: https://github.com/rust-pcap/pcap/blob/main/CONTRIBUTING.md Installs the `grcov` tool, a coverage reporting tool for Rust, using Cargo. ```bash cargo install grcov ``` -------------------------------- ### Type Documentation Example Source: https://github.com/rust-pcap/pcap/blob/main/_autodocs/INDEX.md Shows the standard format for documenting Rust types, including the type definition, description, fields, associated methods, and source location. ```Rust ```rust struct Packet { header: PacketHeader, data: Vec, } ``` **Fields:** | Name | Type | Description | |--------|----------|---------------------------------| | header | PacketHeader | Metadata about the packet | | data | Vec | The raw payload of the packet | ``` ```Rust ```rust impl Packet { // ... methods ... } ``` ``` -------------------------------- ### Build pcap crate on Windows Source: https://github.com/rust-pcap/pcap/blob/main/_autodocs/README.md On Windows, install Npcap and its SDK. Add the SDK's Lib folder to the LIB environment variable and ensure the SDK is in the PATH before building. ```bash 1. Install [Npcap](https://npcap.com/#download) 2. Download [Npcap SDK](https://npcap.com/#download) 3. Add SDK `/Lib` folder to `LIB` environment variable 4. Build with the SDK in PATH ``` -------------------------------- ### Configure Wireless Monitoring (Linux) Source: https://github.com/rust-pcap/pcap/blob/main/_autodocs/configuration.md Example of configuring a Capture object for wireless monitoring on Linux. Enables monitor mode and sets typical parameters for live capture. ```rust #[cfg(target_os = "linux")] let cap = Capture::from_device("wlan0")? .timeout(1000) .snaplen(65535) .buffer_size(10_000_000) .rfmon(true) // Monitor mode .open()?; ``` -------------------------------- ### Generate Documentation with Nightly Toolchain Source: https://github.com/rust-pcap/pcap/blob/main/README.md Use this command to generate documentation with `cfg` labels enabled, assuming the environment variables are set and a nightly toolchain is installed. ```bash cargo +nightly doc --all-features ``` -------------------------------- ### Using BpfProgram::filter to Test Packet Data Source: https://github.com/rust-pcap/pcap/blob/main/_autodocs/api-reference/packet-and-types.md Example demonstrating how to compile a filter and use the `filter` method to check if a packet matches. ```rust let prog = cap.compile("tcp port 80", true)?; let packet_data: &[u8] = &[/* raw packet bytes */]; if prog.filter(packet_data) { println!("Packet matches filter!"); } ``` -------------------------------- ### Open Device for Capture Source: https://github.com/rust-pcap/pcap/blob/main/_autodocs/api-reference/device.md Opens the selected network device for immediate packet capture with default settings. This example demonstrates how to initiate a capture and process incoming packets. ```rust use pcap::Device; let device = Device::lookup().unwrap().unwrap(); match device.open() { Ok(mut capture) => { while let Ok(packet) = capture.next_packet() { println!("Received packet: {} bytes", packet.len()); } }, Err(e) => println!("Error: {}", e), } ``` -------------------------------- ### Batch Packet Transmission Example Source: https://github.com/rust-pcap/pcap/blob/main/_autodocs/api-reference/windows-features.md Demonstrates how to queue and transmit multiple packets efficiently using SendQueue. This method reduces overhead by performing a single user-to-kernel transition for the entire batch. ```rust use pcap::{Capture, Device, Linktype, sendqueue::{SendQueue, SendSync}}; fn main() -> Result<(), Box> { // Get the default device let device = Device::lookup()? .expect("No device available"); let mut cap = device.open()?; // Create a send queue with 10MB capacity let mut queue = SendQueue::new(10 * 1024 * 1024)?; // Prepare some packets (ethernet frames) let packets = vec![ vec![/* ethernet frame 1 */], vec![/* ethernet frame 2 */], vec![/* ethernet frame 3 */], ]; // Queue all packets for packet in packets { queue.queue(None, &packet)?; } println!("Queued {} packets ({} bytes)", queue.len(), queue.len()); // Transmit all packets in a single kernel call queue.transmit(&mut cap, SendSync::Off)?; println!("Transmission complete!"); Ok(()) } ``` -------------------------------- ### Configure Embedded/Low-Memory Systems Source: https://github.com/rust-pcap/pcap/blob/main/_autodocs/configuration.md Example of configuring a Capture object for embedded or low-memory systems. Uses a short timeout, captures only headers, and employs a small buffer. ```rust let cap = Capture::from_device(device)? .timeout(100) // Short timeout .snaplen(256) // Just headers .buffer_size(100_000) // Small buffer .open()?; ``` -------------------------------- ### Build pcap crate on Fedora Linux Source: https://github.com/rust-pcap/pcap/blob/main/_autodocs/README.md On Fedora-based Linux systems, install the `libcap-devel` package before running `cargo build`. ```bash sudo dnf install libpcap-devel cargo build ``` -------------------------------- ### Configure Live Network Capture Source: https://github.com/rust-pcap/pcap/blob/main/_autodocs/configuration.md Example of configuring a Capture object for live network traffic. Sets a timeout, captures full packets, uses a large buffer, and enables promiscuous mode. ```rust use pcap::Device; let device = Device::lookup()?.expect("device"); let cap = Capture::from_device(device)? .timeout(1000) // Don't block forever .snaplen(65535) // Capture full packets .buffer_size(10_000_000) // Large buffer for bursts .promisc(true) // See all traffic (if permitted) .open()?; ``` -------------------------------- ### Savefile::write Method Example Source: https://github.com/rust-pcap/pcap/blob/main/_autodocs/api-reference/packet-and-types.md Writes a packet to the pcap dump file. Use this within a loop to save captured packets. ```rust let mut cap = device.open()?; let mut save = cap.savefile("output.pcap")?; while let Ok(packet) = cap.next_packet() { save.write(&packet); } ``` -------------------------------- ### Rust pcap Configuration Validation Example Source: https://github.com/rust-pcap/pcap/blob/main/_autodocs/configuration.md Demonstrates the two-phase configuration validation in Rust pcap. The first part shows configuration that always succeeds during the inactive phase, while the second part illustrates where errors may occur during the activation phase if the device rejects the configuration. ```rust // This always succeeds: let inactive = Capture::from_device("eth0")? .snaplen(99999999)? // Will fail here .open()?; // Error only happens here: let cap = inactive.open()?; // May fail if device rejects config ``` -------------------------------- ### Configure Offline File Analysis Source: https://github.com/rust-pcap/pcap/blob/main/_autodocs/configuration.md Example of creating a Capture object from a pcap file for offline analysis. No specific configuration is typically needed beyond specifying the file. ```rust use pcap::Capture; let cap = Capture::from_file("traffic.pcap")?; // No configuration needed for offline capture ``` -------------------------------- ### Build pcap crate on Debian Linux Source: https://github.com/rust-pcap/pcap/blob/main/_autodocs/README.md On Debian-based Linux systems, install the `libpcap-dev` package before running `cargo build`. ```bash sudo apt-get install libpcap-dev cargo build ``` -------------------------------- ### Linktype::get_description() Source: https://github.com/rust-pcap/pcap/blob/main/_autodocs/api-reference/packet-and-types.md Gets the human-readable description of a link type. ```APIDOC ## Linktype::get_description() ### Description Gets the human-readable description of a link type. ### Method `get_description()` ### Returns - `Ok(String)` — Description like "Ethernet" - `Err(Error::InvalidLinktype)` — Invalid linktype ### Example ```rust let linktype = Linktype::ETHERNET; println!("Description: {}", linktype.get_description()?); // "Ethernet" ``` ``` -------------------------------- ### Configure High-Performance Monitoring Source: https://github.com/rust-pcap/pcap/blob/main/_autodocs/configuration.md Example of configuring a Capture object for high-performance monitoring. Features a very short timeout, full packet capture, a huge buffer, and immediate mode for minimum latency. ```rust let cap = Capture::from_device(device)? .timeout(10) // Very short timeout .snaplen(65535) // Full packets .buffer_size(50_000_000) // Huge buffer .immediate_mode(true) // Minimum latency .open()?; ``` -------------------------------- ### Writing Network Packets to a File in Rust Source: https://github.com/rust-pcap/pcap/blob/main/_autodocs/README.md Shows how to capture live network packets and save them to a pcap file. This example captures and saves the first 1000 packets. Requires an opened capture device. ```rust let mut cap = device.open()?; let mut savefile = cap.savefile("output.pcap")?; for _ in 0..1000 { if let Ok(packet) = cap.next_packet() { savefile.write(&packet); } } savefile.flush()?; ``` -------------------------------- ### Capture with Nanosecond Precision Source: https://github.com/rust-pcap/pcap/blob/main/_autodocs/types.md Example of opening a pcap file with nanosecond timestamp precision. Ensure your libpcap version supports this feature. ```rust let cap = Capture::from_file_with_precision("file.pcap", Precision::Nano)?; ``` -------------------------------- ### Example: Breaking a Capture Loop Source: https://github.com/rust-pcap/pcap/blob/main/_autodocs/api-reference/capture.md Demonstrates how to use `breakloop_handle` to stop a packet capture loop from a separate thread after a delay. This pattern is useful for controlled capture termination. ```rust let mut cap = device.open()?; let break_handle = cap.breakloop_handle(); std::thread::spawn(move || { std::thread::sleep(std::time::Duration::from_secs(5)); break_handle.breakloop(); }); while let Ok(packet) = cap.next_packet() { println!("Packet: {:?}", packet); } ``` -------------------------------- ### Troubleshooting Linker Errors for libpcap Functions Source: https://github.com/rust-pcap/pcap/blob/main/README.md If you encounter 'cannot find function `pcap_`' errors, it indicates a mismatch between the crate's expected libpcap API and your installed version. This often happens with older libpcap versions. ```text cannot find function `pcap_` in module `raw` ``` -------------------------------- ### Enable Monitor Mode (rfmon) on Wireless Interfaces Source: https://github.com/rust-pcap/pcap/blob/main/_autodocs/configuration.md Enables monitor mode (rfmon) on wireless interfaces, allowing capture of all 802.11 frames regardless of BSSID. This feature is Unix/Linux only and typically requires root privileges. Ensure wireless driver support and appropriate setup (e.g., `iw set monitor` on Linux). ```rust #[cfg(not(windows))] pub fn rfmon(self, to: bool) -> Capture ``` ```rust #[cfg(target_os = "linux")] let cap = Capture::from_device("wlan0")? .rfmon(true) // Monitor raw 802.11 .open()?; ``` -------------------------------- ### Get Linktype Name Source: https://github.com/rust-pcap/pcap/blob/main/_autodocs/api-reference/packet-and-types.md Retrieves the string name for a given link type. Use this to get a human-readable identifier like "EN10MB" for Ethernet. ```rust pub fn get_name(&self) -> Result ``` ```rust let linktype = Linktype::ETHERNET; println!("Name: {}", linktype.get_name()?); // "EN10MB" ``` -------------------------------- ### Basic Capture Configuration Pattern Source: https://github.com/rust-pcap/pcap/blob/main/_autodocs/configuration.md Demonstrates the fluent/chainable configuration of a capture object before activation. Ensure all desired configurations are set before calling `.open()`. ```rust use pcap::{Capture, Device}; let cap = Capture::from_device(device)? .timeout(1000) // Set timeout .snaplen(5000) // Set capture size .promisc(true) // Enable promiscuous mode .buffer_size(2000000) // Set buffer .open()?; // Activate after configuration ``` -------------------------------- ### Get maximum queue capacity Source: https://github.com/rust-pcap/pcap/blob/main/_autodocs/api-reference/windows-features.md Returns the maximum capacity of the queue in bytes. ```rust pub fn maxlen(&self) -> u32 ``` -------------------------------- ### Get current queue size Source: https://github.com/rust-pcap/pcap/blob/main/_autodocs/api-reference/windows-features.md Returns the current number of bytes used in the queue. ```rust pub fn len(&self) -> u32 ``` -------------------------------- ### Get Savefile Version Source: https://github.com/rust-pcap/pcap/blob/main/_autodocs/INDEX.md Retrieves the pcap file format version from an opened savefile. ```rust use pcap::Capture; fn main() { let mut cap = Capture::from_file("file.pcap").unwrap(); println!("Pcap file version: {:?}", cap.version()); } ``` -------------------------------- ### Linktype::get_name() Source: https://github.com/rust-pcap/pcap/blob/main/_autodocs/api-reference/packet-and-types.md Gets the name of the link type (e.g., "EN10MB" for Ethernet). ```APIDOC ## Linktype::get_name() ### Description Gets the name of the link type (e.g., "EN10MB" for Ethernet). ### Method `get_name()` ### Returns - `Ok(String)` — Name like "EN10MB" - `Err(Error::InvalidLinktype)` — Invalid linktype ### Example ```rust let linktype = Linktype::ETHERNET; println!("Name: {}", linktype.get_name()?); // "EN10MB" ``` ``` -------------------------------- ### Basic Live Packet Capture in Rust Source: https://github.com/rust-pcap/pcap/blob/main/_autodocs/README.md Demonstrates how to find the default network device and capture packets in real-time. Requires the 'pcap' crate. ```rust use pcap::Device; fn main() -> Result<(), Box> { // Find default device let device = Device::lookup()? .expect("no device found"); // Open and read packets let mut cap = device.open()?; while let Ok(packet) = cap.next_packet() { println!("Packet: {} bytes", packet.len()); } Ok(()) } ``` -------------------------------- ### Get Capture Statistics Source: https://github.com/rust-pcap/pcap/blob/main/_autodocs/INDEX.md Retrieves capture statistics, including the number of packets received, dropped, and dropped by the interface. ```rust use pcap::{Device, Capture, Config}; fn main() { let mut cap = Capture::from_device(Device::list().unwrap().next().unwrap()) .unwrap() .with_config(Config { timeout: std::time::Duration::from_secs(1), ..Default::default() }) .build() .unwrap(); let stats = cap.stats().unwrap(); println!("Capture stats: {:?}", stats); } ``` -------------------------------- ### Handle Device Not Available Source: https://github.com/rust-pcap/pcap/blob/main/_autodocs/errors.md Demonstrates how to handle the case where no network device is available. Device absence is signaled by `Ok(None)`, not a `Result::Err`. ```rust let device = Device::lookup() .expect("Lookup failed") .expect("No device available"); // This is where device absence appears ``` -------------------------------- ### Accessing Capture Mutably Source: https://github.com/rust-pcap/pcap/blob/main/_autodocs/api-reference/packet-and-types.md Get a mutable reference to the inner Capture object from a PacketIter to directly manipulate capture settings. ```rust let cap = device.open()?; let mut iter = cap.iter(MyCodec); // Can access capture directly iter.capture_mut().filter("tcp port 80", true)?; ``` -------------------------------- ### Set Datalink Type for Capture Source: https://github.com/rust-pcap/pcap/blob/main/_autodocs/api-reference/capture.md Configures the datalink layer type for the capture handle. This should be done before starting packet capture. ```rust cap.set_datalink(Linktype::ETHERNET)?; ``` -------------------------------- ### BpfProgram::get_instructions() Source: https://github.com/rust-pcap/pcap/blob/main/_autodocs/api-reference/packet-and-types.md Returns a slice of the compiled BPF instructions. ```APIDOC ## BpfProgram::get_instructions() ### Description Returns a slice of the compiled BPF instructions. ### Method `get_instructions` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Response #### Success Response - **&[BpfInstruction]**: Slice of `BpfInstruction` values ``` -------------------------------- ### Configuring Packet Capture in Rust Source: https://github.com/rust-pcap/pcap/blob/main/_autodocs/README.md Shows how to configure capture parameters such as promiscuous mode, snaplen, timeout, and buffer size before opening the capture device. Requires the 'pcap' crate. ```rust use pcap::{Capture, Device}; let cap = Capture::from_device(device)? .promisc(true) .snaplen(5000) .timeout(1000) .buffer_size(10_000_000) .open()?; ``` -------------------------------- ### Setting Capabilities for Non-Root Users on Linux Source: https://github.com/rust-pcap/pcap/blob/main/README.md If not running as root, you need to set specific capabilities for the binary to function correctly. This command grants network raw and admin capabilities. ```bash sudo setcap cap_net_raw,cap_net_admin=eip path/to/bin ``` -------------------------------- ### Get Linktype Description Source: https://github.com/rust-pcap/pcap/blob/main/_autodocs/api-reference/packet-and-types.md Retrieves a human-readable description for a link type. This provides more context than the name, such as "Ethernet" for Linktype::ETHERNET. ```rust pub fn get_description(&self) -> Result ``` -------------------------------- ### Get Win32 Event Handle Source: https://github.com/rust-pcap/pcap/blob/main/_autodocs/INDEX.md Retrieves the Win32 event handle associated with a capture device. This is useful for synchronizing with other Windows-specific I/O operations. ```rust use pcap::{Device, Capture, Config}; fn main() { let mut cap = Capture::from_device(Device::list().unwrap().next().unwrap()) .unwrap() .with_config(Config { timeout: std::time::Duration::from_secs(1), ..Default::default() }) .build() .unwrap(); // This method is only available on Windows. // let event_handle = cap.get_event(); // println!("Win32 event handle: {:?}", event_handle); println!("get_event() called (Windows specific)."); } ``` -------------------------------- ### List All Available Devices Source: https://github.com/rust-pcap/pcap/blob/main/_autodocs/api-reference/device.md Enumerates all network devices known to pcap. Prints the name and description of each device, handling potential errors during the listing process. ```rust use pcap::Device; match Device::list() { Ok(devices) => { for device in devices { println!("Device: {} ({})", device.name, device.desc.unwrap_or_default()); } }, Err(e) => println!("Error: {}", e), } ``` -------------------------------- ### Enable Immediate Mode for Capture Device Source: https://github.com/rust-pcap/pcap/blob/main/_autodocs/configuration.md Enables immediate mode for a capture device to return packets as soon as they arrive, minimizing latency. This is useful for real-time monitoring but may increase CPU usage. Requires libpcap 1.5.0+ or specific Windows implementations. ```rust pub fn immediate_mode(self, to: bool) -> Capture ``` ```rust // Real-time monitoring with minimum latency let cap = Capture::from_device(device)? .immediate_mode(true) .open()?; ``` -------------------------------- ### Get Datalink Type Source: https://github.com/rust-pcap/pcap/blob/main/_autodocs/api-reference/capture.md Retrieves the current datalink type for a capture handle. This is useful for understanding the network interface's data link layer protocol. ```rust pub fn get_datalink(&self) -> Linktype ``` -------------------------------- ### Set Environment Variables for Documentation Generation Source: https://github.com/rust-pcap/pcap/blob/main/README.md Set these environment variables before generating documentation to enable `cfg` labels. This requires a nightly Rust toolchain. ```bash RUSTFLAGS="--cfg docsrs" RUSTDOCFLAGS="--cfg docsrs" ``` -------------------------------- ### List All Devices and Their Properties in Rust Source: https://github.com/rust-pcap/pcap/blob/main/_autodocs/api-reference/device.md Iterates through all available network devices, printing their names, descriptions, flags, and addresses. Requires the `pcap` crate and the `Device` struct. ```rust use pcap::Device; fn main() -> Result<(), Box> { for device in Device::list()? { println!("Device: {}", device.name); if let Some(desc) = &device.desc { println!(" Description: {}", desc); } println!(" Flags: {:?}", device.flags); for addr in &device.addresses { println!(" Address: {}", addr.addr); if let Some(nm) = addr.netmask { println!(" Netmask: {}", nm); } } } Ok(()) } ``` -------------------------------- ### Handle InvalidInputString Error Source: https://github.com/rust-pcap/pcap/blob/main/_autodocs/errors.md This example demonstrates how to catch and report errors caused by input strings containing null bytes, which are incompatible with C-style string handling. ```rust match Capture::filter("tcp port 80\0invalid", true) { Err(Error::InvalidInputString) => { eprintln!("Input string contains null byte"); } Err(e) => eprintln!("Error: {}", e), Ok(()) => { /* ... */ } } ``` -------------------------------- ### Windows Batch Packet Transmission in Rust Source: https://github.com/rust-pcap/pcap/blob/main/_autodocs/README.md Demonstrates how to queue multiple packets for transmission and send them all at once using SendSync::Off on Windows. Requires the 'pcap' crate and a capture device. ```rust use pcap::sendqueue::{SendQueue, SendSync}; let mut queue = SendQueue::new(10 * 1024 * 1024)?; queue.queue(None, &packet1)?; queue.queue(None, &packet2)?; queue.queue(None, &packet3)?; queue.transmit(&mut cap, SendSync::Off)?; ``` -------------------------------- ### Handling InvalidString for Null Pointers Source: https://github.com/rust-pcap/pcap/blob/main/_autodocs/errors.md Handle this error when libpcap returns a null pointer where a string was expected, such as for device names. This may indicate a libpcap installation issue. ```rust match Device::lookup() { Err(Error::InvalidString) => { eprintln!("Device returned null name - libpcap error"); } Err(e) => eprintln!("Error: {}", e), Ok(device_opt) => { /* ... */ } } ``` -------------------------------- ### Create Device from String Name Source: https://github.com/rust-pcap/pcap/blob/main/_autodocs/api-reference/device.md Creates a Device from a string device name. Useful for quick device creation without looking up device properties. ```rust impl From<&str> for Device { fn from(name: &str) -> Self } ``` ```rust use pcap::Device; let device = Device::from("eth0"); let capture = device.open().unwrap(); ``` -------------------------------- ### Create Savefile for Packet Writing Source: https://github.com/rust-pcap/pcap/blob/main/_autodocs/api-reference/capture.md Initializes a Savefile context to write captured packets to a specified file path. Ensure the path is valid and writable. ```rust cap.savefile("output.pcap")?; ``` -------------------------------- ### List Network Devices Source: https://github.com/rust-pcap/pcap/blob/main/_autodocs/INDEX.md Use `Device::list()` to enumerate available network interfaces. This function returns a `Vec` containing details about each network device. ```rust use pcap::Device; fn main() { let mut devs = Device::list().unwrap(); let dev = devs.next().unwrap(); println!("{:?}", dev); } ``` -------------------------------- ### Create Send Queue Source: https://github.com/rust-pcap/pcap/blob/main/_autodocs/INDEX.md Creates a new `SendQueue` for batch transmission of packets on Windows. This queue manages packets to be sent. ```rust use pcap::windows::SendQueue; fn main() { let mut queue = SendQueue::new(); println!("Created SendQueue with len: {}, maxlen: {}", queue.len(), queue.maxlen()); } ``` -------------------------------- ### BreakLoop::breakloop Method Example Source: https://github.com/rust-pcap/pcap/blob/main/_autodocs/api-reference/packet-and-types.md Interrupts a blocking capture loop by calling pcap_breakloop. This is safe to call from signal handlers or other threads. Note the safety considerations for signal handlers. ```rust let break_handle = cap.breakloop_handle(); std::thread::spawn(move || { std::thread::sleep(std::time::Duration::from_secs(5)); break_handle.breakloop(); // Safe from any thread }); // Blocking loop will unblock after 5 seconds while let Ok(packet) = cap.next_packet() { println!("Packet: {:?}", packet); } ``` -------------------------------- ### immediate_mode(enable) Source: https://github.com/rust-pcap/pcap/blob/main/_autodocs/configuration.md Enables or disables immediate mode on the capture device. When enabled, packets are returned as soon as they arrive, minimizing latency but potentially increasing CPU usage. This is useful for real-time monitoring applications. ```APIDOC ## immediate_mode(enable) ### Description Enables or disables immediate mode on the capture device. When enabled, packets are returned as soon as they arrive, minimizing latency but potentially increasing CPU usage. This is useful for real-time monitoring applications. ### Method `self.immediate_mode(to: bool)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```rust // Real-time monitoring with minimum latency let cap = Capture::from_device(device)? .immediate_mode(true) .open()?; ``` ### Response #### Success Response (200) Returns a `Capture` object with immediate mode configured. #### Response Example None explicitly defined, returns `Capture`. ``` -------------------------------- ### Configuration Methods Source: https://github.com/rust-pcap/pcap/blob/main/_autodocs/api-reference/capture.md Methods for configuring capture parameters before activation. These methods consume self and return a new Capture for chaining. ```APIDOC ## timeout() ### Description Sets the read timeout in milliseconds. Default is 0 (block indefinitely). Non-zero values prevent indefinite blocking on macOS. ### Signature ```rust pub fn timeout(self, ms: i32) -> Capture ``` ### Parameters #### Path Parameters - **ms** (i32) - Required - Timeout in milliseconds ``` ```APIDOC ## snaplen() ### Description Sets the maximum length of a packet to capture into the buffer. Useful if you only want certain headers without the entire packet. ### Signature ```rust pub fn snaplen(self, to: i32) -> Capture ``` ### Parameters #### Path Parameters - **to** (i32) - Required - Maximum capture length in bytes ``` ```APIDOC ## promisc() ### Description Sets promiscuous mode on or off. Default is off. ### Signature ```rust pub fn promisc(self, to: bool) -> Capture ``` ### Parameters #### Path Parameters - **to** (bool) - Required - Enable promiscuous mode ``` ```APIDOC ## immediate_mode() ### Description Sets immediate mode on or off. Default is off. When enabled, packets are returned immediately rather than buffered. ### Signature ```rust pub fn immediate_mode(self, to: bool) -> Capture ``` ### Parameters #### Path Parameters - **to** (bool) - Required - Enable immediate mode ### Note On WinPcap, immediate mode is set through `min_to_copy(0)`. Calling `min_to_copy` with non-zero after `immediate_mode` will disable it. ``` ```APIDOC ## buffer_size() ### Description Sets the buffer size for incoming packet data. Default is 1000000 bytes. Should be larger than snaplen. ### Signature ```rust pub fn buffer_size(self, to: i32) -> Capture ``` ### Parameters #### Path Parameters - **to** (i32) - Required - Buffer size in bytes ``` ```APIDOC ## rfmon() ### Description Sets monitor mode (rfmon) on or off. Not available on Windows. ### Signature ```rust #[cfg(not(windows))] pub fn rfmon(self, to: bool) -> Capture ``` ### Parameters #### Path Parameters - **to** (bool) - Required - Enable monitor mode ``` ```APIDOC ## tstamp_type() ### Description Sets the timestamp type to be used by the capture device. ### Signature ```rust #[cfg(libpcap_1_2_1)] pub fn tstamp_type(self, tstamp_type: TimestampType) -> Capture ``` ### Parameters #### Path Parameters - **tstamp_type** (TimestampType) - Required - The desired timestamp type ``` ```APIDOC ## precision() ### Description Sets the timestamp precision returned in captures. ### Signature ```rust #[cfg(libpcap_1_5_0)] pub fn precision(self, precision: Precision) -> Capture ``` ### Parameters #### Path Parameters - **precision** (Precision) - Required - Micro (default) or Nano precision ``` -------------------------------- ### Create a new SendQueue Source: https://github.com/rust-pcap/pcap/blob/main/_autodocs/api-reference/windows-features.md Initializes a new SendQueue with a specified maximum buffer size. Use `packet_header_size()` to determine header size for pre-calculation. Headers are implicitly added. ```rust use pcap::sendqueue::SendQueue; // Allocate 1MB buffer let mut queue = SendQueue::new(1024 * 1024)?; ``` -------------------------------- ### BpfProgram::get_instructions Method Signature Source: https://github.com/rust-pcap/pcap/blob/main/_autodocs/api-reference/packet-and-types.md Provides the method signature for retrieving the compiled BPF instructions as a slice. ```rust pub fn get_instructions(&self) -> &[BpfInstruction] ``` -------------------------------- ### Device::open() Source: https://github.com/rust-pcap/pcap/blob/main/_autodocs/api-reference/device.md Opens a packet capture session on the specified device with default settings. This method returns an active `Capture` handle, enabling immediate packet capture, or a `pcap` error if the device cannot be opened. ```APIDOC ## Device::open() ### Description Opens a `Capture` on this device, allowing immediate packet capture with default settings. This is a convenience method equivalent to `Capture::from_device(device)?.open()`. ### Method `device.open()` ### Returns - `Ok(Capture)` — An active capture handle - `Err(Error)` — Device could not be opened ### Example ```rust use pcap::Device; let device = Device::lookup().unwrap().unwrap(); match device.open() { Ok(mut capture) => { while let Ok(packet) = capture.next_packet() { println!("Received packet: {} bytes", packet.len()); } }, Err(e) => println!("Error: {}", e), } ``` ``` -------------------------------- ### PacketCodec Trait and Decode Method Source: https://github.com/rust-pcap/pcap/blob/main/_autodocs/api-reference/packet-and-types.md Defines the PacketCodec trait for custom packet decoding. The decode method transforms a raw Packet into a user-defined type. An example implementation shows how to convert packet data into a hex string. ```rust pub trait PacketCodec { type Item; fn decode(&mut self, packet: Packet<'_>) -> Self::Item; } ``` ```rust impl PacketCodec for HexCodec { type Item = String; fn decode(&mut self, packet: Packet) -> String { packet.data .iter() .map(|b| format!("{:02x}", b)) .collect::>() .join(":") } } ``` ```rust // Use with iterator let cap = device.open()?; for result in cap.iter(HexCodec) { println!("Packet (hex): {}", result?); } ``` -------------------------------- ### Get Capture Event Handle (Windows) Source: https://github.com/rust-pcap/pcap/blob/main/_autodocs/api-reference/windows-features.md Retrieves a Win32 event handle for the capture context. This is useful for integrating with Win32 event loops or for multi-threaded capture coordination. The returned HANDLE is owned by the Capture context and cannot be closed by the caller. ```rust #[cfg(windows)] pub unsafe fn get_event(&self) -> HANDLE ``` ```rust use pcap::Device; let cap = Device::lookup()?.unwrap().open()?; let event = unsafe { cap.get_event() }; // Can pass event to WaitForMultipleObjects or other Win32 APIs ``` -------------------------------- ### Set Immediate Mode Source: https://github.com/rust-pcap/pcap/blob/main/_autodocs/api-reference/capture.md Enables or disables immediate mode, which returns packets as soon as they arrive rather than buffering them. Note that on WinPcap, this is controlled by `min_to_copy(0)`. ```rust cap.immediate_mode(true) ``` -------------------------------- ### Open Network Device for Capture Source: https://github.com/rust-pcap/pcap/blob/main/_autodocs/INDEX.md Opens a network device for capturing packets. Requires a `Device` object obtained from `Device::list()`. ```rust use pcap::{Device, Capture, Config}; fn main() { let mut cap = Capture::from_device(Device::list().unwrap().next().unwrap()) .unwrap() .build() .unwrap(); } ``` -------------------------------- ### Reading Network Packets from a File in Rust Source: https://github.com/rust-pcap/pcap/blob/main/_autodocs/README.md Demonstrates how to open a pcap file and read packets from it sequentially. Useful for offline analysis. Requires the 'pcap' crate. ```rust use pcap::Capture; let mut cap = Capture::from_file("traffic.pcap")?; while let Ok(packet) = cap.next_packet() { println!("{:?}", packet.header); } ``` -------------------------------- ### Build pcap crate on macOS Source: https://github.com/rust-pcap/pcap/blob/main/_autodocs/README.md On macOS, libpcap is included by default. Simply run `cargo build` to compile the crate. ```bash # libpcap is included by default cargo build ``` -------------------------------- ### Check if Device is Up Source: https://github.com/rust-pcap/pcap/blob/main/_autodocs/api-reference/device.md Returns true if this device is up. This indicates the network interface is enabled. ```rust pub fn is_up(&self) -> bool ``` -------------------------------- ### Open Savefile for Reading Source: https://github.com/rust-pcap/pcap/blob/main/_autodocs/INDEX.md Opens a pcap dump file for reading packet data. Use this for offline analysis. ```rust use pcap::Capture; fn main() { let mut cap = Capture::from_file("file.pcap").unwrap(); let packet = cap.next_packet().unwrap(); println!("Read packet: {} bytes", packet.len()); } ``` -------------------------------- ### Device Structure Source: https://github.com/rust-pcap/pcap/blob/main/_autodocs/types.md Outlines the composition of a `Device` type. ```rust Device ├── Address ├── DeviceFlags │ ├── IfFlags (bitflags) │ └── ConnectionStatus └── ... ``` -------------------------------- ### Clean Project and Compile Tests Source: https://github.com/rust-pcap/pcap/blob/main/CONTRIBUTING.md Cleans previous build artifacts and compiles the project with code coverage instrumentation enabled. It sets `RUSTFLAGS` for coverage and `LLVM_PROFILE_FILE` to specify the output path for raw profile data. ```bash rm -rf ./target/debug/{coverage,profraw} cargo clean -p pcap env RUSTFLAGS="-C instrument-coverage" \ LLVM_PROFILE_FILE="target/debug/profraw/pcap-%p-%m.profraw" \ cargo test --all-features --all-targets ``` -------------------------------- ### Set Minimum Copy Size for Capture (Windows) Source: https://github.com/rust-pcap/pcap/blob/main/_autodocs/api-reference/windows-features.md Configures the minimum amount of data to be received by the kernel before returning packets to the application. Setting to 0 enables immediate mode. Only available on Windows. ```rust #[cfg(windows)] pub fn min_to_copy(self, to: i32) -> Capture ``` -------------------------------- ### Set Minimum Bytes to Copy (Windows) Source: https://github.com/rust-pcap/pcap/blob/main/_autodocs/configuration.md Sets the minimum data size before the kernel returns packets on Windows. Use 0 for immediate mode. ```rust #[cfg(windows)] pub fn min_to_copy(self, to: i32) -> Capture ``` ```rust // Windows-specific: Immediate mode let cap = Capture::from_device(device)? .min_to_copy(0) .open()?; ``` -------------------------------- ### Open Code Coverage Report Source: https://github.com/rust-pcap/pcap/blob/main/CONTRIBUTING.md Opens the generated HTML code coverage report in the default web browser. ```bash xdg-open target/debug/coverage/index.html ``` -------------------------------- ### Device::from Source: https://github.com/rust-pcap/pcap/blob/main/_autodocs/api-reference/device.md Creates a Device from a string device name. This is useful for quickly creating a Device object without needing to look up its properties. ```APIDOC ## Device::from ### Description Creates a Device from a string device name. Useful for quick device creation without looking up device properties. ### Signature ```rust impl From<&str> for Device { fn from(name: &str) -> Self } ``` ### Example ```rust use pcap::Device; let device = Device::from("eth0"); let capture = device.open().unwrap(); ``` ``` -------------------------------- ### Build pcap crate with custom libpcap location Source: https://github.com/rust-pcap/pcap/blob/main/_autodocs/README.md If libpcap is not found automatically, you can specify its location using the `LIBPCAP_LIBDIR` environment variable. You can also specify a version with `LIBPCAP_VER`. ```bash # Via environment variable export LIBPCAP_LIBDIR=/opt/pcap/lib cargo build ``` ```bash # Via environment variable (explicit version) export LIBPCAP_VER=1.10.0 cargo build ``` -------------------------------- ### Capture::from_device Source: https://github.com/rust-pcap/pcap/blob/main/_autodocs/api-reference/capture.md Opens an inactive capture handle for a specified device, allowing for configuration before activation. ```APIDOC ## Capture::from_device() ### Description Opens an inactive capture handle for a device. The handle is configured but not yet active, allowing you to set parameters before activation. ### Signature ```rust pub fn from_device>(device: D) -> Result, Error> ``` ### Parameters #### Path Parameters - **device** (Device or &str) - Required - The device to capture from, or its name ### Returns - `Ok(Capture)` — Inactive handle ready for configuration - `Err(Error)` — Device could not be opened ### Example ```rust use pcap::{Capture, Device}; let device = Device::lookup().unwrap().unwrap(); let cap = Capture::from_device(device) .unwrap() .promisc(true) .snaplen(5000) .timeout(1000); ``` ``` -------------------------------- ### Windows-Specific Features Source: https://github.com/rust-pcap/pcap/blob/main/_autodocs/INDEX.md Details Windows-specific APIs for packet queuing and transmission, including `SendQueue` and `SendSync`. ```APIDOC ## Windows-Specific Features ### Description Details Windows-specific APIs for packet queuing and transmission, including `SendQueue` and `SendSync`. ### SendQueue Methods - `new()`: Create a new batch queue for sending packets. - `queue()`: Add a single packet to the queue. - `queue_sg()`: Add a scattered packet (using scatter-gather I/O) to the queue. - `transmit()`: Send all queued packets. - Queue management methods: `len()`, `maxlen()`, `is_empty()`, `reset()`. ### SendSync Enum - `Off`: Immediate transmission (Windows only). - `On`: Timed transmission (Windows only). ### Capture Windows Methods - `min_to_copy()`: Sets the minimum amount of data to copy before returning from a read operation. - `get_event()`: Retrieves the Win32 event handle associated with the capture. ### Details - Performance analysis. - Buffer sizing guidelines. - Complete examples. - Practical usage patterns. - Error handling. ``` -------------------------------- ### Handle Permission Denied Error Source: https://github.com/rust-pcap/pcap/blob/main/_autodocs/errors.md Checks for and handles 'permission denied' errors when opening a network device. This typically requires elevated privileges. ```rust // Error message: "libpcap error: You don't have permission..." match device.open() { Err(Error::PcapError(msg)) if msg.contains("permission") => { eprintln!("Need elevated privileges"); std::process::exit(1); } Err(e) => eprintln!("Error: {}", e), Ok(cap) => { /* ... */ } } ``` -------------------------------- ### Handle Packet Queueing Errors Source: https://github.com/rust-pcap/pcap/blob/main/_autodocs/api-reference/windows-features.md Demonstrates how to handle potential errors when queuing a packet, including insufficient memory and buffer overflow conditions. ```rust match queue.queue(None, &packet) { Ok(()) => println!("Packet queued"), Err(Error::InsufficientMemory) => println!("Queue full, transmit now"), Err(Error::BufferOverflow) => println!("Packet too large"), Err(e) => println!("Error: {}", e), } ``` -------------------------------- ### Packet Capture Flow Diagram Source: https://github.com/rust-pcap/pcap/blob/main/_autodocs/README.md Illustrates the sequence of operations for capturing network packets, from device listing to active capture. ```text Device::list() → Device {name, desc, addresses, flags} ↓ Device::open() or Capture::from_device() ↓ Capture {configurable state} ├─ timeout(ms) ├─ snaplen(bytes) ├─ promisc(bool) ├─ buffer_size(bytes) └─ ... (8 more configuration methods) ↓ Capture::open() ↓ Capture {live interface capture} ├─ next_packet() → Result ├─ sendpacket(buf) → Result<()> ├─ filter(bpf_str, optimize) → Result<()> ├─ stats() → Result └─ setnonblock() → Result> ``` -------------------------------- ### DeviceFlags::empty Source: https://github.com/rust-pcap/pcap/blob/main/_autodocs/api-reference/device.md Creates a new DeviceFlags instance with all flags and connection status unset. ```APIDOC ## DeviceFlags::empty() ### Description Creates a new DeviceFlags with all flags unset. ### Signature ```rust pub fn empty() -> Self ``` ``` -------------------------------- ### compile() Source: https://github.com/rust-pcap/pcap/blob/main/_autodocs/api-reference/capture.md Compiles a BPF filter string into a program without setting it on the capture handle. ```APIDOC ## compile() ### Description Compiles a BPF filter string into a program without setting it. ### Method `compile(&self, program: &str, optimize: bool) -> Result` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response `Ok(BpfProgram)` — Compiled filter program #### Error Response `Err(Error)` — Compilation failed #### Response Example None ``` -------------------------------- ### Manually Setting libpcap Version for Static Linking Source: https://github.com/rust-pcap/pcap/blob/main/README.md If automatic detection fails or you are linking statically, manually specify the libpcap version using the LIBPCAP_VER environment variable. This is useful when using older libpcap versions. ```bash env LIBPCAP_VER=1.5.0 ``` -------------------------------- ### Read and Filter Packets from a Savefile Source: https://github.com/rust-pcap/pcap/blob/main/_autodocs/api-reference/packet-and-types.md Opens a pcap file, applies a BPF filter for 'tcp port 80', and then iterates through the matching packets, printing their length and header information. The filter is applied immediately upon creation. ```rust use pcap::Capture; fn main() -> Result<(), Box> { let mut cap = Capture::from_file("traffic.pcap")?; cap.filter("tcp port 80", true)?; while let Ok(packet) = cap.next_packet() { println!("Packet: {} bytes at {:?}", packet.len(), packet.header); } Ok(()) } ``` -------------------------------- ### savefile() Source: https://github.com/rust-pcap/pcap/blob/main/_autodocs/api-reference/capture.md Creates a Savefile context, enabling the writing of captured packets to a specified file. ```APIDOC ## savefile() ### Description Creates a Savefile context for writing captured packets to a file. ### Method `savefile>(&self, path: P) -> Result` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response `Ok(Savefile)` — Savefile handle #### Error Response `Err(Error)` — File could not be created #### Response Example None ``` -------------------------------- ### min_to_copy() Source: https://github.com/rust-pcap/pcap/blob/main/_autodocs/api-reference/windows-features.md Sets the minimum amount of data that must be received by the kernel in a single call before returning packets to the application. This is a Windows-specific setting. ```APIDOC ## min_to_copy() ### Description Sets the minimum amount of data that must be received by the kernel in a single call before returning packets to the application. Setting to 0 enables immediate mode. ### Method `#[cfg(windows)] pub fn min_to_copy(self, to: i32) -> Capture` ### Parameters #### Path Parameters - **to** (i32) - Required - Minimum bytes to accumulate (0 = immediate mode) ### Notes - Setting to 0 enables immediate mode - Setting immediate_mode(true) internally calls this with 0 - Calling with non-zero after immediate_mode(true) disables immediate mode - Only available on Windows ``` -------------------------------- ### Set LIBPCAP_LIBDIR Environment Variable Source: https://github.com/rust-pcap/pcap/blob/main/_autodocs/configuration.md Specifies the directory for libpcap when dynamic linking. Use when libpcap is in a non-standard location or pkg-config cannot find it. ```bash env LIBPCAP_LIBDIR=/opt/pcap/lib cargo build ``` -------------------------------- ### Capture::open Source: https://github.com/rust-pcap/pcap/blob/main/_autodocs/api-reference/capture.md Activates the inactive capture handle, making it ready for packet capture. ```APIDOC ## open() ### Description Activates the inactive capture handle for packet capture. ### Signature ```rust pub fn open(self) -> Result, Error> ``` ### Returns - `Ok(Capture)` — Active capture handle - `Err(Error)` — Activation failed ### Example ```rust use pcap::{Capture, Device}; let cap = Capture::from_device(Device::lookup().unwrap().unwrap()) .unwrap() .promisc(true) .snaplen(5000) .open() .unwrap(); ``` ``` -------------------------------- ### Compile BPF Filter Program Source: https://github.com/rust-pcap/pcap/blob/main/_autodocs/api-reference/capture.md Compiles a BPF filter string into a BpfProgram without applying it to the capture device. Useful for pre-compiling filters. ```rust cap.compile("tcp port 80", true)?; ``` -------------------------------- ### Set Operating System Buffer Size Source: https://github.com/rust-pcap/pcap/blob/main/_autodocs/configuration.md Configures the operating system's buffer size for incoming packet data. A larger buffer reduces packet loss under heavy traffic but increases memory usage. The buffer size must be larger than `snaplen` to be effective. ```rust // High-traffic network - large buffer let cap = Capture::from_device(device)? .buffer_size(10_000_000) // 10MB .open()?; // Embedded device - small buffer let cap = Capture::from_device(device)? .buffer_size(100_000) // 100KB .open()?; ``` -------------------------------- ### Check if Device is Running Source: https://github.com/rust-pcap/pcap/blob/main/_autodocs/api-reference/device.md Returns true if this device is running. This signifies that the network interface is active and operational. ```rust pub fn is_running(&self) -> bool ```