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