Struct 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() 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 cap = Capture::from_device(Device::lookup().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() {
    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.

Examples found in repository?
examples/savefile.rs (line 24)
5fn main() {
6	{
7		// open capture from default device
8		let mut cap = Capture::from_device(Device::lookup().unwrap()).unwrap().open().unwrap();
9
10		// open savefile using the capture
11		let mut savefile = cap.savefile("test.pcap").unwrap();
12
13		// get a packet from the interface
14		let p = cap.next().unwrap();
15
16		// print the packet out
17		println!("packet received on network: {:?}", p);
18
19		// write the packet to the savefile
20		savefile.write(&p);
21	}
22
23	// open a new capture from the test.pcap file we wrote to above
24	let mut cap = Capture::from_file("test.pcap").unwrap();
25
26	// get a packet
27	let p = cap.next().unwrap();
28
29	// print that packet out -- it should be the same as the one we printed above
30	println!("packet obtained from file: {:?}", p);
31}
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§

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().

Examples found in repository?
examples/listenlocalhost.rs (line 6)
3fn main() {
4    // listen on the device named "any", which is only available on Linux. This is only for
5    // demonstration purposes.
6    let mut cap = pcap::Capture::from_device("any").unwrap().open().unwrap();
7
8    // filter out all packets that don't have 127.0.0.1 as a source or destination.
9    cap.filter("host 127.0.0.1").unwrap();
10
11    while let Ok(packet) = cap.next() {
12    	println!("got packet! {:?}", packet);
13    }
14}
More examples
Hide additional examples
examples/savefile.rs (line 8)
5fn main() {
6	{
7		// open capture from default device
8		let mut cap = Capture::from_device(Device::lookup().unwrap()).unwrap().open().unwrap();
9
10		// open savefile using the capture
11		let mut savefile = cap.savefile("test.pcap").unwrap();
12
13		// get a packet from the interface
14		let p = cap.next().unwrap();
15
16		// print the packet out
17		println!("packet received on network: {:?}", p);
18
19		// write the packet to the savefile
20		savefile.write(&p);
21	}
22
23	// open a new capture from the test.pcap file we wrote to above
24	let mut cap = Capture::from_file("test.pcap").unwrap();
25
26	// get a packet
27	let p = cap.next().unwrap();
28
29	// print that packet out -- it should be the same as the one we printed above
30	println!("packet obtained from file: {:?}", p);
31}
Source

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

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

Examples found in repository?
examples/listenlocalhost.rs (line 6)
3fn main() {
4    // listen on the device named "any", which is only available on Linux. This is only for
5    // demonstration purposes.
6    let mut cap = pcap::Capture::from_device("any").unwrap().open().unwrap();
7
8    // filter out all packets that don't have 127.0.0.1 as a source or destination.
9    cap.filter("host 127.0.0.1").unwrap();
10
11    while let Ok(packet) = cap.next() {
12    	println!("got packet! {:?}", packet);
13    }
14}
More examples
Hide additional examples
examples/savefile.rs (line 8)
5fn main() {
6	{
7		// open capture from default device
8		let mut cap = Capture::from_device(Device::lookup().unwrap()).unwrap().open().unwrap();
9
10		// open savefile using the capture
11		let mut savefile = cap.savefile("test.pcap").unwrap();
12
13		// get a packet from the interface
14		let p = cap.next().unwrap();
15
16		// print the packet out
17		println!("packet received on network: {:?}", p);
18
19		// write the packet to the savefile
20		savefile.write(&p);
21	}
22
23	// open a new capture from the test.pcap file we wrote to above
24	let mut cap = Capture::from_file("test.pcap").unwrap();
25
26	// get a packet
27	let p = cap.next().unwrap();
28
29	// print that packet out -- it should be the same as the one we printed above
30	println!("packet obtained from file: {:?}", p);
31}
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, t: TstampType) -> 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 rfmon(self, to: bool) -> Capture<Inactive>

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

This is not available on Windows.

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>

§Activated captures include Capture<Active> and Capture<Offline>.

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.

Examples found in repository?
examples/savefile.rs (line 11)
5fn main() {
6	{
7		// open capture from default device
8		let mut cap = Capture::from_device(Device::lookup().unwrap()).unwrap().open().unwrap();
9
10		// open savefile using the capture
11		let mut savefile = cap.savefile("test.pcap").unwrap();
12
13		// get a packet from the interface
14		let p = cap.next().unwrap();
15
16		// print the packet out
17		println!("packet received on network: {:?}", p);
18
19		// write the packet to the savefile
20		savefile.write(&p);
21	}
22
23	// open a new capture from the test.pcap file we wrote to above
24	let mut cap = Capture::from_file("test.pcap").unwrap();
25
26	// get a packet
27	let p = cap.next().unwrap();
28
29	// print that packet out -- it should be the same as the one we printed above
30	println!("packet obtained from file: {:?}", p);
31}
Source

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

Set the direction of the capture

Source

pub fn next<'a>(&'a mut self) -> Result<Packet<'a>, 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. 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 of this next() method.

Examples found in repository?
examples/easylisten.rs (line 8)
3fn main() {
4    // get the default Device
5    let mut cap = pcap::Device::lookup().unwrap().open().unwrap();
6
7    // get a packet and print its bytes
8    println!("{:?}", cap.next());
9}
More examples
Hide additional examples
examples/getstatistics.rs (line 9)
3fn main() {
4    // get the default Device
5    let mut cap = pcap::Device::lookup().unwrap().open().unwrap();
6
7    // get 10 packets
8    for _ in 0..10 {
9      cap.next().ok();
10    }
11    let stats = cap.stats().unwrap();
12    println!("Received: {}, dropped: {}, if_dropped: {}", stats.received, stats.dropped, stats.if_dropped);
13}
examples/getdevices.rs (line 12)
3fn main() {
4    // list all of the devices pcap tells us are available
5    for device in pcap::Device::list().unwrap() {
6        println!("Found device! {:?}", device);
7
8        // now you can create a Capture with this Device if you want.
9        let mut cap = device.open().unwrap();
10
11        // get a packet from this capture
12        let packet = cap.next();
13
14        println!("got a packet! {:?}", packet);
15    }
16}
examples/listenlocalhost.rs (line 11)
3fn main() {
4    // listen on the device named "any", which is only available on Linux. This is only for
5    // demonstration purposes.
6    let mut cap = pcap::Capture::from_device("any").unwrap().open().unwrap();
7
8    // filter out all packets that don't have 127.0.0.1 as a source or destination.
9    cap.filter("host 127.0.0.1").unwrap();
10
11    while let Ok(packet) = cap.next() {
12    	println!("got packet! {:?}", packet);
13    }
14}
examples/savefile.rs (line 14)
5fn main() {
6	{
7		// open capture from default device
8		let mut cap = Capture::from_device(Device::lookup().unwrap()).unwrap().open().unwrap();
9
10		// open savefile using the capture
11		let mut savefile = cap.savefile("test.pcap").unwrap();
12
13		// get a packet from the interface
14		let p = cap.next().unwrap();
15
16		// print the packet out
17		println!("packet received on network: {:?}", p);
18
19		// write the packet to the savefile
20		savefile.write(&p);
21	}
22
23	// open a new capture from the test.pcap file we wrote to above
24	let mut cap = Capture::from_file("test.pcap").unwrap();
25
26	// get a packet
27	let p = cap.next().unwrap();
28
29	// print that packet out -- it should be the same as the one we printed above
30	println!("packet obtained from file: {:?}", p);
31}
Source

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

Adds a filter to the capture using the given BPF program string. Internally this is compiled using pcap_compile().

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

Examples found in repository?
examples/listenlocalhost.rs (line 9)
3fn main() {
4    // listen on the device named "any", which is only available on Linux. This is only for
5    // demonstration purposes.
6    let mut cap = pcap::Capture::from_device("any").unwrap().open().unwrap();
7
8    // filter out all packets that don't have 127.0.0.1 as a source or destination.
9    cap.filter("host 127.0.0.1").unwrap();
10
11    while let Ok(packet) = cap.next() {
12    	println!("got packet! {:?}", packet);
13    }
14}
Source

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

Examples found in repository?
examples/getstatistics.rs (line 11)
3fn main() {
4    // get the default Device
5    let mut cap = pcap::Device::lookup().unwrap().open().unwrap();
6
7    // get 10 packets
8    for _ in 0..10 {
9      cap.next().ok();
10    }
11    let stats = cap.stats().unwrap();
12    println!("Received: {}, dropped: {}, if_dropped: {}", stats.received, stats.dropped, stats.if_dropped);
13}
Source§

impl Capture<Active>

Source

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

Sends a packet over this capture handle’s interface.

Source§

impl Capture<Dead>

Source

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

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

Trait Implementations§

Source§

impl AsRawFd for Capture<Active>

Source§

fn as_raw_fd(&self) -> RawFd

Extracts the raw file descriptor. Read more
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.

Auto Trait Implementations§

§

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

§

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

§

impl<T> Send for Capture<T>
where T: Send + ?Sized,

§

impl<T> Sync for Capture<T>
where T: Sync + ?Sized,

§

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

§

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

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>,

Source§

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>,

Source§

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.