Struct pcap::Capture

source ·
pub struct Capture<T: State + ?Sized> { /* private fields */ }
Expand description

This is a pcap capture handle which is an abstraction over the pcap_t provided by pcap. There are many ways to instantiate and interact with a pcap handle, so phantom types are used to express these behaviors.

Capture<Inactive> is created via Capture::from_device(). This handle is inactive, so you cannot (yet) obtain packets from it. However, you can configure things like the buffer size, snaplen, timeout, and promiscuity before you activate it.

Capture<Active> is created by calling .open() on a Capture<Inactive>. This activates the capture handle, allowing you to get packets with .next_packet() or apply filters with .filter().

Capture<Offline> is created via Capture::from_file(). This allows you to read a pcap format dump file as if you were opening an interface – very useful for testing or analysis.

Capture<Dead> is created via Capture::dead(). This allows you to create a pcap format dump file without needing an active capture.

Example:

let mut cap = Capture::from_device(Device::lookup().unwrap().unwrap()) // open the "default" interface
              .unwrap() // assume the device exists and we are authorized to open it
              .open() // activate the handle
              .unwrap(); // assume activation worked

while let Ok(packet) = cap.next_packet() {
    println!("received packet! {:?}", packet);
}

Implementations§

source§

impl Capture<Offline>

source

pub fn from_file<P: AsRef<Path>>(path: P) -> Result<Capture<Offline>, Error>

Opens an offline capture handle from a pcap dump file, given a path.

source

pub fn from_file_with_precision<P: AsRef<Path>>( path: P, precision: Precision ) -> Result<Capture<Offline>, Error>

Opens an offline capture handle from a pcap dump file, given a path. Takes an additional precision argument specifying the time stamp precision desired.

source

pub unsafe fn from_raw_fd(fd: RawFd) -> Result<Capture<Offline>, Error>

Opens an offline capture handle from a pcap dump file, given a file descriptor.

Safety

Unsafe, because the returned Capture assumes it is the sole owner of the file descriptor.

source

pub unsafe fn from_raw_fd_with_precision( fd: RawFd, precision: Precision ) -> Result<Capture<Offline>, Error>

Opens an offline capture handle from a pcap dump file, given a file descriptor. Takes an additional precision argument specifying the time stamp precision desired.

Safety

Unsafe, because the returned Capture assumes it is the sole owner of the file descriptor.

source

pub fn major_version(&self) -> i32

Get the major version number of the pcap dump file format.

source

pub fn minor_version(&self) -> i32

Get the minor version number of the pcap dump file format.

source

pub fn version(&self) -> (i32, i32)

Get the (major, minor) version number of the pcap dump file format.

source§

impl Capture<Inactive>

source

pub fn from_device<D: Into<Device>>( device: D ) -> Result<Capture<Inactive>, Error>

Opens a capture handle for a device. You can pass a Device or an &str device name here. The handle is inactive, but can be activated via .open().

Example
use pcap::*;

// Usage 1: Capture from a single owned device
let dev: Device = pcap::Device::lookup()
    .expect("device lookup failed")
    .expect("no device available");
let cap1 = Capture::from_device(dev);

// Usage 2: Capture from an element of device list.
let list: Vec<Device> = pcap::Device::list().unwrap();
let cap2 = Capture::from_device(list[0].clone());

// Usage 3: Capture from `&str` device name
let cap3 = Capture::from_device("eth0");
source

pub fn open(self) -> Result<Capture<Active>, Error>

Activates an inactive capture created from Capture::from_device() or returns an error.

source

pub fn timeout(self, ms: i32) -> Capture<Inactive>

Set the read timeout for the Capture. By default, this is 0, so it will block indefinitely.

source

pub fn tstamp_type(self, tstamp_type: TimestampType) -> Capture<Inactive>

Set the time stamp type to be used by a capture device.

source

pub fn promisc(self, to: bool) -> Capture<Inactive>

Set promiscuous mode on or off. By default, this is off.

source

pub fn immediate_mode(self, to: bool) -> Capture<Inactive>

Set immediate mode on or off. By default, this is off.

Note that in WinPcap immediate mode is set by passing a 0 argument to min_to_copy. Immediate mode will be unset if min_to_copy is later called with a non-zero argument. Immediate mode is unset by resetting min_to_copy to the WinPcap default possibly changing a previously set value. When using min_to_copy, it is best to avoid immediate_mode.

source

pub fn rfmon(self, to: bool) -> Capture<Inactive>

Set rfmon mode on or off. The default is maintained by pcap.

source

pub fn buffer_size(self, to: i32) -> Capture<Inactive>

Set the buffer size for incoming packet data.

The default is 1000000. This should always be larger than the snaplen.

source

pub fn precision(self, precision: Precision) -> Capture<Inactive>

Set the time stamp precision returned in captures.

source

pub fn snaplen(self, to: i32) -> Capture<Inactive>

Set the snaplen size (the maximum length of a packet captured into the buffer). Useful if you only want certain headers, but not the entire packet.

The default is 65535.

source§

impl<T: Activated + ?Sized> Capture<T>

List the datalink types that this captured device supports.

Set the datalink type for the current capture handle.

Get the current datalink type for this capture handle.

source

pub fn savefile<P: AsRef<Path>>(&self, path: P) -> Result<Savefile, Error>

Create a Savefile context for recording captured packets using this Capture’s configurations.

source

pub unsafe fn savefile_raw_fd(&self, fd: RawFd) -> Result<Savefile, Error>

Create a Savefile context for recording captured packets using this Capture’s configurations. The output is written to a raw file descriptor which is opened in "w" mode.

Safety

Unsafe, because the returned Savefile assumes it is the sole owner of the file descriptor.

source

pub fn savefile_append<P: AsRef<Path>>( &self, path: P ) -> Result<Savefile, Error>

Reopen a Savefile context for recording captured packets using this Capture’s configurations. This is similar to savefile() but does not create the file if it does not exist and, if it does already exist, and is a pcap file with the same byte order as the host opening the file, and has the same time stamp precision, link-layer header type, and snapshot length as p, it will write new packets at the end of the file.

source

pub fn direction(&self, direction: Direction) -> Result<(), Error>

Set the direction of the capture

source

pub fn next_packet(&mut self) -> Result<Packet<'_>, Error>

Blocks until a packet is returned from the capture handle or an error occurs.

pcap captures packets and places them into a buffer which this function reads from.

Warning

This buffer has a finite length, so if the buffer fills completely new packets will be discarded temporarily. This means that in realtime situations, you probably want to minimize the time between calls to next_packet() method.

source

pub fn iter<C: PacketCodec>(self, codec: C) -> PacketIter<T, C>

Return an iterator that call Self::next_packet() forever. Require a PacketCodec

source

pub fn stream<C: PacketCodec>( self, codec: C ) -> Result<PacketStream<T, C>, Error>

Returns this capture as a [futures::Stream] of packets.

Errors

If this capture is set to be blocking, or if the network device does not support select(), an error will be returned.

source

pub fn filter(&mut self, program: &str, optimize: bool) -> Result<(), Error>

Sets the filter on the capture using the given BPF program string. Internally this is compiled using pcap_compile(). optimize controls whether optimization on the resulting code is performed

See http://biot.com/capstats/bpf.html for more information about this syntax.

source

pub fn stats(&mut self) -> Result<Stat, Error>

Get capture statistics about this capture. The values represent packet statistics from the start of the run to the time of the call.

See https://www.tcpdump.org/manpages/pcap_stats.3pcap.html for per-platform caveats about how packet statistics are calculated.

source§

impl Capture<Active>

source

pub fn sendpacket<B: Borrow<[u8]>>(&mut self, buf: B) -> Result<(), Error>

Sends a packet over this capture handle’s interface.

source

pub fn setnonblock(self) -> Result<Capture<Active>, Error>

Set the capture to be non-blocking. When this is set, Self::next_packet() may return an error indicating that there is no packet available to be read.

source§

impl Capture<Dead>

source

pub fn dead(linktype: Linktype) -> Result<Capture<Dead>, Error>

Creates a “fake” capture handle for the given link type.

source

pub fn dead_with_precision( linktype: Linktype, precision: Precision ) -> Result<Capture<Dead>, Error>

Creates a “fake” capture handle for the given link type and timestamp precision.

source

pub fn compile( &self, program: &str, optimize: bool ) -> Result<BpfProgram, Error>

Compiles the string into a filter program using pcap_compile.

Trait Implementations§

source§

impl AsRawFd for Capture<Active>

source§

fn as_raw_fd(&self) -> RawFd

Returns the file descriptor for a live capture.

source§

impl<T: State + ?Sized> Drop for Capture<T>

source§

fn drop(&mut self)

Executes the destructor for this type. Read more
source§

impl<T: Activated> From<Capture<T>> for Capture<dyn Activated>

source§

fn from(cap: Capture<T>) -> Capture<dyn Activated>

Converts to this type from the input type.
source§

impl<T: State + ?Sized> From<NonNull<pcap_t>> for Capture<T>

source§

fn from(handle: NonNull<pcap_t>) -> Self

Converts to this type from the input type.
source§

impl<S: Activated + ?Sized + 'static> IntoIterator for Capture<S>

§

type IntoIter = PacketLendingIter<S>

The type of the returned iterator
source§

fn into_iter(self) -> Self::IntoIter

Convert this value into an Iterator
source§

impl<T: State + ?Sized> Send for Capture<T>

Auto Trait Implementations§

§

impl<T: ?Sized> RefUnwindSafe for Capture<T>
where T: RefUnwindSafe,

§

impl<T> !Sync for Capture<T>

§

impl<T: ?Sized> Unpin for Capture<T>
where T: Unpin,

§

impl<T: ?Sized> UnwindSafe for Capture<T>
where T: UnwindSafe,

Blanket Implementations§

source§

impl<T> Any for T
where T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T, U> Into<U> for T
where U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.