Skip to main content

rustnet_core/network/interface_stats/
mod.rs

1use std::io;
2use std::time::SystemTime;
3
4#[cfg(any(target_os = "macos", target_os = "freebsd"))]
5mod bsd;
6#[cfg(target_os = "linux")]
7mod linux;
8#[cfg(target_os = "windows")]
9mod windows;
10
11#[cfg(target_os = "freebsd")]
12use bsd::FreeBSDStatsProvider;
13#[cfg(target_os = "macos")]
14use bsd::MacOSStatsProvider;
15#[cfg(target_os = "linux")]
16use linux::LinuxStatsProvider;
17#[cfg(target_os = "windows")]
18use windows::WindowsStatsProvider;
19#[cfg(target_os = "windows")]
20pub use windows::capture_interface_alias;
21
22/// Statistics for a network interface
23#[derive(Debug, Clone)]
24pub struct InterfaceStats {
25    pub interface_name: String,
26    pub rx_bytes: u64,
27    pub tx_bytes: u64,
28    pub rx_packets: u64,
29    pub tx_packets: u64,
30    pub rx_errors: u64,
31    pub tx_errors: u64,
32    pub rx_dropped: u64,
33    pub tx_dropped: u64,
34    pub collisions: u64,
35    pub timestamp: SystemTime,
36}
37
38impl InterfaceStats {
39    /// Calculate rates from two snapshots
40    pub fn calculate_rates(&self, previous: &InterfaceStats) -> InterfaceRates {
41        let duration = self
42            .timestamp
43            .duration_since(previous.timestamp)
44            .unwrap_or_default()
45            .as_secs_f64();
46
47        if duration == 0.0 {
48            return InterfaceRates::default();
49        }
50
51        InterfaceRates {
52            rx_bytes_per_sec: ((self.rx_bytes.saturating_sub(previous.rx_bytes)) as f64 / duration)
53                as u64,
54            tx_bytes_per_sec: ((self.tx_bytes.saturating_sub(previous.tx_bytes)) as f64 / duration)
55                as u64,
56        }
57    }
58
59    /// Calculate traffic transferred between two cumulative snapshots.
60    pub fn traffic_since(&self, previous: &InterfaceStats) -> InterfaceTrafficWindow {
61        let sampled_for = self
62            .timestamp
63            .duration_since(previous.timestamp)
64            .unwrap_or_default();
65
66        if sampled_for.is_zero() {
67            return InterfaceTrafficWindow::default();
68        }
69
70        InterfaceTrafficWindow {
71            rx_bytes: self.rx_bytes.saturating_sub(previous.rx_bytes),
72            tx_bytes: self.tx_bytes.saturating_sub(previous.tx_bytes),
73        }
74    }
75}
76
77/// Rate calculations for interface statistics
78#[derive(Debug, Clone, Default)]
79pub struct InterfaceRates {
80    pub rx_bytes_per_sec: u64,
81    pub tx_bytes_per_sec: u64,
82}
83
84/// Traffic transferred over a rolling interface-counter window.
85#[derive(Debug, Clone, Default)]
86pub struct InterfaceTrafficWindow {
87    pub rx_bytes: u64,
88    pub tx_bytes: u64,
89}
90
91/// Trait for platform-specific interface statistics providers
92pub trait InterfaceStatsProvider: Send + Sync {
93    /// Get statistics for all available interfaces
94    fn get_all_stats(&self) -> Result<Vec<InterfaceStats>, io::Error>;
95}
96
97/// Create the interface-stats provider for the current platform: sysfs on
98/// Linux, `getifaddrs` on macOS/FreeBSD, the IP Helper API on Windows.
99/// The composition point for front-ends, mirroring
100/// `rustnet_host::create_process_lookup`.
101#[cfg(any(
102    target_os = "linux",
103    target_os = "macos",
104    target_os = "freebsd",
105    target_os = "windows"
106))]
107pub fn create_stats_provider() -> Box<dyn InterfaceStatsProvider> {
108    #[cfg(target_os = "linux")]
109    {
110        Box::new(LinuxStatsProvider)
111    }
112    #[cfg(target_os = "macos")]
113    {
114        Box::new(MacOSStatsProvider)
115    }
116    #[cfg(target_os = "freebsd")]
117    {
118        Box::new(FreeBSDStatsProvider)
119    }
120    #[cfg(target_os = "windows")]
121    {
122        Box::new(WindowsStatsProvider)
123    }
124}
125
126#[cfg(test)]
127mod tests {
128    use super::*;
129    use std::time::Duration;
130
131    /// Snapshot with the given counters and timestamp, error fields zeroed.
132    fn stats(
133        rx_bytes: u64,
134        tx_bytes: u64,
135        rx_packets: u64,
136        tx_packets: u64,
137        timestamp: SystemTime,
138    ) -> InterfaceStats {
139        InterfaceStats {
140            interface_name: "test".to_string(),
141            rx_bytes,
142            tx_bytes,
143            rx_packets,
144            tx_packets,
145            rx_errors: 0,
146            tx_errors: 0,
147            rx_dropped: 0,
148            tx_dropped: 0,
149            collisions: 0,
150            timestamp,
151        }
152    }
153
154    #[test]
155    fn test_rate_calculation() {
156        let t1 = SystemTime::now();
157        let t2 = t1 + Duration::from_secs(1);
158
159        let stats1 = stats(1000, 500, 10, 5, t1);
160        let stats2 = stats(2000, 1000, 20, 10, t2);
161
162        let rates = stats2.calculate_rates(&stats1);
163        assert_eq!(rates.rx_bytes_per_sec, 1000);
164        assert_eq!(rates.tx_bytes_per_sec, 500);
165    }
166
167    #[test]
168    fn test_rate_calculation_zero_duration() {
169        let t = SystemTime::now();
170
171        let stats1 = stats(1000, 500, 10, 5, t);
172        let stats2 = stats1.clone();
173
174        let rates = stats2.calculate_rates(&stats1);
175        assert_eq!(rates.rx_bytes_per_sec, 0);
176        assert_eq!(rates.tx_bytes_per_sec, 0);
177    }
178
179    #[test]
180    fn test_rate_calculation_with_counter_wrapping() {
181        let t1 = SystemTime::now();
182        let t2 = t1 + Duration::from_secs(1);
183
184        let stats1 = stats(1000, 500, 10, 5, t1);
185
186        // Simulate counter reset (should use saturating_sub to avoid panic):
187        // counters lower than the previous snapshot's.
188        let stats2 = stats(500, 250, 5, 2, t2);
189
190        let rates = stats2.calculate_rates(&stats1);
191        // Should result in 0 due to saturating_sub
192        assert_eq!(rates.rx_bytes_per_sec, 0);
193        assert_eq!(rates.tx_bytes_per_sec, 0);
194    }
195
196    #[test]
197    fn test_traffic_since() {
198        let t1 = SystemTime::now();
199        let t2 = t1 + Duration::from_secs(60);
200        let first = stats(1_000, 500, 0, 0, t1);
201        let second = InterfaceStats {
202            rx_bytes: 9_000,
203            tx_bytes: 2_500,
204            timestamp: t2,
205            ..first.clone()
206        };
207
208        let window = second.traffic_since(&first);
209        assert_eq!(window.rx_bytes, 8_000);
210        assert_eq!(window.tx_bytes, 2_000);
211    }
212}