cross_socket/pcap/
listener.rs

1use crate::packet::PacketFrame;
2use crate::pcap::capture::start_capture;
3use crate::pcap::PacketCaptureOptions;
4use std::sync::mpsc::{channel, Receiver, Sender};
5use std::sync::{Arc, Mutex};
6
7/// Listner
8#[derive(Debug)]
9pub struct Listner {
10    /// Packet capture options
11    pub options: PacketCaptureOptions,
12    /// Message Sender
13    pub tx: Arc<Mutex<Sender<PacketFrame>>>,
14    /// Message Receiver
15    pub rx: Arc<Mutex<Receiver<PacketFrame>>>,
16    /// Stop handle
17    pub stop: Arc<Mutex<bool>>,
18    /// Packets store
19    pub packets: Arc<Mutex<Vec<PacketFrame>>>,
20}
21
22impl Listner {
23    /// Create new Listner
24    pub fn new(options: PacketCaptureOptions) -> Listner {
25        let (tx, rx) = channel();
26        let listener: Listner = Listner {
27            options: options,
28            tx: Arc::new(Mutex::new(tx)),
29            rx: Arc::new(Mutex::new(rx)),
30            stop: Arc::new(Mutex::new(false)),
31            packets: Arc::new(Mutex::new(Vec::new())),
32        };
33        listener
34    }
35
36    /// Get progress receiver
37    pub fn get_receiver(&self) -> Arc<Mutex<Receiver<PacketFrame>>> {
38        self.rx.clone()
39    }
40
41    /// Get stop handle
42    pub fn get_stop_handle(&self) -> Arc<Mutex<bool>> {
43        self.stop.clone()
44    }
45
46    // Get packets
47    pub fn get_packets(&self) -> Vec<PacketFrame> {
48        self.packets.lock().unwrap().clone()
49    }
50
51    /// Start capture
52    pub fn start(&self) {
53        let options = self.options.clone();
54        let packets: Vec<PacketFrame> = start_capture(options, &self.tx, &self.stop);
55        for packet in packets {
56            self.packets.lock().unwrap().push(packet);
57        }
58    }
59}