File: iterprint.rs

package info (click to toggle)
rust-pcap 2.2.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 584 kB
  • sloc: makefile: 2
file content (41 lines) | stat: -rw-r--r-- 990 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
//! Example of using iterators that print paquet
use pcap::{Capture, Device, Packet, PacketCodec, PacketHeader};
use std::error;

/// Represents a owned packet
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PacketOwned {
    pub header: PacketHeader,
    pub data: Box<[u8]>,
}

/// Simple codec that tranform [`pcap::Packet`] into [`PacketOwned`]
pub struct Codec;

impl PacketCodec for Codec {
    type Item = PacketOwned;

    fn decode(&mut self, packet: Packet) -> Self::Item {
        PacketOwned {
            header: *packet.header,
            data: packet.data.into(),
        }
    }
}

fn main() -> Result<(), Box<dyn error::Error>> {
    let device = Device::lookup()?.ok_or("no device available")?;

    // get the default Device
    println!("Using device {}", device.name);

    let cap = Capture::from_device(device)?.immediate_mode(true).open()?;

    for packet in cap.iter(Codec) {
        let packet = packet?;

        println!("{:?}", packet);
    }

    Ok(())
}