File: stdin.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 (54 lines) | stat: -rw-r--r-- 1,241 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
42
43
44
45
46
47
48
49
50
51
52
53
54
//! Example of reading a pcap dump file stream from stdin. This is useful
//! for integrating with other tools, such as tcpdump. For example,
//!
//!    tcpdump -i en0 -U -w - | cargo run --example stdin
//!

#[cfg(not(windows))]
mod inner {
    use pcap::{Packet, PacketCodec, PacketHeader};

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

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

#[cfg(not(windows))]
fn main() -> Result<(), Box<dyn std::error::Error>> {
    use inner::*;
    use pcap::Capture;
    use std::{io, os::unix::io::AsRawFd};

    let stdin = io::stdin();

    let cap = unsafe { Capture::from_raw_fd(stdin.as_raw_fd())? };

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

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

    Ok(())
}

#[cfg(windows)]
fn main() -> Result<(), Box<dyn std::error::Error>> {
    eprintln!("Program not supported on Windows");
    Ok(())
}