|
| 1 | +use pcap::{Capture, Active, Device,Error as PcapError,Address}; |
| 2 | +use std::time::Instant; |
| 3 | + |
| 4 | +#[derive(Debug)] |
| 5 | +pub enum CaptureError { |
| 6 | + Cap(PcapError), |
| 7 | + Other(String), |
| 8 | + DeviceNotFound(String), |
| 9 | + InitializationError(String), |
| 10 | + InvalidDeviceIndex(String), |
| 11 | +} |
| 12 | + |
| 13 | +impl From<pcap::Error> for CaptureError { |
| 14 | + fn from(err: PcapError) -> Self { |
| 15 | + CaptureError::Cap(err) |
| 16 | + } |
| 17 | +} |
| 18 | + |
| 19 | +impl From<String> for CaptureError { |
| 20 | + fn from(err: String) -> Self { |
| 21 | + CaptureError::Other(err) |
| 22 | + } |
| 23 | +} |
| 24 | + |
| 25 | +pub struct CaptureDevice{ |
| 26 | + pub name: String, |
| 27 | + pub desc: String, |
| 28 | + pub address: Vec<Address>, |
| 29 | + pub capture: Capture<Active>, |
| 30 | +} |
| 31 | + |
| 32 | +impl CaptureDevice{ |
| 33 | + pub fn new(device: Device) -> Result<CaptureDevice, CaptureError> { |
| 34 | + let capture = initialize_capture(device.clone())?; |
| 35 | + |
| 36 | + Ok(CaptureDevice { |
| 37 | + name: device.name, |
| 38 | + desc: device.desc.as_deref().unwrap_or("").to_string(), |
| 39 | + address: device.addresses, |
| 40 | + capture, |
| 41 | + }) |
| 42 | + } |
| 43 | +} |
| 44 | +pub fn list_devices() -> Result<Vec<Device>, CaptureError> { |
| 45 | + Ok(Device::list().map_err(CaptureError::Cap)?) |
| 46 | +} |
| 47 | +pub fn find_device(identifier: &str) -> Result<Device, CaptureError> { |
| 48 | + let start = Instant::now(); |
| 49 | + println!("Requested Device: {}", identifier); |
| 50 | + |
| 51 | + let devices = list_devices()?; |
| 52 | + |
| 53 | + if let Ok(index) = identifier.parse::<usize>() { |
| 54 | + if let Some(device) = devices.get(index) { |
| 55 | + let duration = start.elapsed(); |
| 56 | + println!("Device {} captured in {:?}", device.name, duration); |
| 57 | + return Ok(device.clone()); |
| 58 | + } else { |
| 59 | + return Err(CaptureError::InvalidDeviceIndex(identifier.to_string())); |
| 60 | + } |
| 61 | + } |
| 62 | + |
| 63 | + for device in devices { |
| 64 | + if device.name == identifier { |
| 65 | + let duration = start.elapsed(); |
| 66 | + println!("{} device captured in {:?}", identifier, duration); |
| 67 | + return Ok(device); |
| 68 | + } |
| 69 | + } |
| 70 | + |
| 71 | + Err(CaptureError::DeviceNotFound(identifier.to_string())) |
| 72 | +} |
| 73 | + |
| 74 | +fn initialize_capture(device: Device) -> Result<Capture<Active>, CaptureError> { |
| 75 | + Capture::from_device(device) |
| 76 | + .map_err(CaptureError::Cap)? |
| 77 | + .promisc(true) |
| 78 | + .snaplen(1024) |
| 79 | + .timeout(60000) |
| 80 | + .immediate_mode(true) |
| 81 | + .open() |
| 82 | + .map_err(|_| CaptureError::InitializationError("Capture initialization error".into())) |
| 83 | +} |
0 commit comments