1use core::{fmt, time::Duration};
17use std::{net::IpAddr, time::Instant};
18
19use crate::{Bytes, Error, Rate, Result};
20
21#[derive(Clone, Debug, PartialEq, Eq)]
23#[non_exhaustive]
24pub struct Interface {
25 pub name: String,
27 pub index: u32,
29 pub description: Option<String>,
31 pub kind: InterfaceKind,
33 pub mac: Option<Mac>,
35 pub addresses: Vec<IpNet>,
37 pub up: bool,
39 pub running: bool,
41 pub mtu: Option<u32>,
43 pub speed_mbps: Option<u64>,
45 pub is_physical: bool,
47}
48
49#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
51#[non_exhaustive]
52pub enum InterfaceKind {
53 Ethernet,
55 Wifi,
57 Loopback,
59 Tunnel,
61 Bridge,
63 Virtual,
65 Cellular,
67 Other,
69}
70
71#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
74#[non_exhaustive]
75pub struct Mac {
76 pub bytes: [u8; 6],
78 pub kind: MacKind,
80}
81
82impl Mac {
83 #[allow(dead_code)] pub(crate) fn from_bytes(bytes: [u8; 6]) -> Mac {
87 let kind = if bytes[0] & 0x02 != 0 {
88 MacKind::Random
89 } else {
90 MacKind::Permanent
91 };
92 Mac { bytes, kind }
93 }
94}
95
96impl fmt::Display for Mac {
97 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
99 let b = self.bytes;
100 write!(
101 f,
102 "{:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}",
103 b[0], b[1], b[2], b[3], b[4], b[5]
104 )
105 }
106}
107
108#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
110#[non_exhaustive]
111pub enum MacKind {
112 Permanent,
114 Random,
116 Unknown,
118}
119
120#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
122pub struct IpNet {
123 pub addr: IpAddr,
125 pub prefix: u8,
127}
128
129impl fmt::Display for IpNet {
130 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
132 write!(f, "{}/{}", self.addr, self.prefix)
133 }
134}
135
136#[derive(Clone, Copy, Debug)]
138#[non_exhaustive]
139pub struct InterfaceOptions {
140 pub include_down: bool,
142 pub include_loopback: bool,
144 pub details: bool,
147 pub max_interfaces: usize,
149}
150
151impl Default for InterfaceOptions {
152 fn default() -> Self {
153 InterfaceOptions {
154 include_down: true,
155 include_loopback: true,
156 details: true,
157 max_interfaces: 4_096,
158 }
159 }
160}
161
162pub fn interfaces() -> Result<Vec<Interface>> {
177 interfaces_with(InterfaceOptions::default())
178}
179
180pub fn interfaces_with(options: InterfaceOptions) -> Result<Vec<Interface>> {
188 let mut list = crate::sys::interfaces(&options)?;
189 list.retain(|i| {
190 (options.include_down || i.up)
191 && (options.include_loopback || i.kind != InterfaceKind::Loopback)
192 });
193 list.sort_by(|a, b| a.index.cmp(&b.index).then_with(|| a.name.cmp(&b.name)));
194 Ok(list)
195}
196
197pub fn addresses() -> Result<Vec<IpAddr>> {
209 let options = InterfaceOptions {
210 include_down: false,
211 include_loopback: false,
212 details: false,
213 ..InterfaceOptions::default()
214 };
215 let mut out: Vec<IpAddr> = interfaces_with(options)?
216 .into_iter()
217 .flat_map(|i| i.addresses)
218 .map(|n| n.addr)
219 .filter(|a| !a.is_loopback() && !is_link_local(a))
220 .collect();
221 out.dedup();
222 Ok(out)
223}
224
225fn is_link_local(addr: &IpAddr) -> bool {
226 match addr {
227 IpAddr::V4(v4) => v4.is_link_local(),
228 IpAddr::V6(v6) => (v6.segments()[0] & 0xffc0) == 0xfe80,
229 }
230}
231
232#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
234#[non_exhaustive]
235pub struct Totals {
236 pub received: Bytes,
238 pub sent: Bytes,
240 pub packets_received: u64,
242 pub packets_sent: u64,
244 pub errors: u64,
246 pub dropped: u64,
248}
249
250#[derive(Clone, Copy, PartialEq, Debug)]
252#[non_exhaustive]
253pub struct Traffic {
254 pub download: Rate,
256 pub upload: Rate,
258 pub packets_in_per_sec: f64,
260 pub packets_out_per_sec: f64,
262 pub interval: Duration,
264}
265
266#[derive(Clone, Debug, PartialEq)]
268#[non_exhaustive]
269pub struct InterfaceTraffic {
270 pub interface: String,
272 pub traffic: Traffic,
274}
275
276#[derive(Clone, Debug, PartialEq, Eq)]
278#[non_exhaustive]
279pub struct Counters {
280 pub interface: String,
282 pub received: Bytes,
284 pub sent: Bytes,
286 pub packets_received: u64,
288 pub packets_sent: u64,
290 pub errors_in: u64,
292 pub errors_out: u64,
294 pub dropped_in: u64,
296 pub dropped_out: u64,
298}
299
300impl Totals {
301 #[allow(dead_code)] pub(crate) fn add(&mut self, c: &Counters) {
304 self.received = self.received.saturating_add(c.received);
305 self.sent = self.sent.saturating_add(c.sent);
306 self.packets_received = self.packets_received.saturating_add(c.packets_received);
307 self.packets_sent = self.packets_sent.saturating_add(c.packets_sent);
308 self.errors = self
309 .errors
310 .saturating_add(c.errors_in)
311 .saturating_add(c.errors_out);
312 self.dropped = self
313 .dropped
314 .saturating_add(c.dropped_in)
315 .saturating_add(c.dropped_out);
316 }
317
318 fn since(&self, earlier: &Totals, interval: Duration) -> Traffic {
321 let d = |new: u64, old: u64| new.saturating_sub(old);
322 let secs = interval.as_secs_f64();
323 let per_sec = |n: u64| if secs > 0.0 { n as f64 / secs } else { 0.0 };
324 Traffic {
325 download: Rate::from_delta(d(self.received.raw(), earlier.received.raw()), interval),
326 upload: Rate::from_delta(d(self.sent.raw(), earlier.sent.raw()), interval),
327 packets_in_per_sec: per_sec(d(self.packets_received, earlier.packets_received)),
328 packets_out_per_sec: per_sec(d(self.packets_sent, earlier.packets_sent)),
329 interval,
330 }
331 }
332}
333
334impl Counters {
335 fn as_totals(&self) -> Totals {
336 let mut t = Totals::default();
337 t.add(self);
338 t
339 }
340}
341
342pub const DEFAULT_WINDOW: Duration = Duration::from_secs(1);
344
345const MIN_WINDOW: Duration = Duration::from_millis(100);
346const MAX_WINDOW: Duration = Duration::from_secs(60);
347
348pub fn totals() -> Result<Totals> {
362 crate::sys::net_totals()
363}
364
365pub fn counters() -> Result<Vec<Counters>> {
371 crate::sys::net_counters()
372}
373
374pub fn traffic() -> Result<Traffic> {
388 traffic_over(DEFAULT_WINDOW)
389}
390
391pub fn traffic_over(window: Duration) -> Result<Traffic> {
398 let mut sampler = Sampler::totals_only()?;
399 std::thread::sleep(window.clamp(MIN_WINDOW, MAX_WINDOW));
400 sampler.sample()
401}
402
403#[derive(Debug)]
422pub struct Sampler {
423 total: Totals,
424 at: Instant,
425 interfaces: Vec<Counters>,
426 interfaces_at: Instant,
427}
428
429impl Sampler {
430 pub fn new() -> Result<Sampler> {
436 let now = Instant::now();
437 Ok(Sampler {
438 total: totals()?,
439 at: now,
440 interfaces: counters()?,
441 interfaces_at: now,
442 })
443 }
444
445 fn totals_only() -> Result<Sampler> {
446 let now = Instant::now();
447 Ok(Sampler {
448 total: totals()?,
449 at: now,
450 interfaces: Vec::new(),
451 interfaces_at: now,
452 })
453 }
454
455 pub fn sample(&mut self) -> Result<Traffic> {
463 let now = totals()?;
464 let at = Instant::now();
465 let interval = at.duration_since(self.at);
466 if interval.is_zero() {
467 return Err(too_soon(interval));
468 }
469 let traffic = now.since(&self.total, interval);
470 self.total = now;
471 self.at = at;
472 Ok(traffic)
473 }
474
475 pub fn sample_per_interface(&mut self) -> Result<Vec<InterfaceTraffic>> {
483 let now = counters()?;
484 let at = Instant::now();
485 let interval = at.duration_since(self.interfaces_at);
486 if interval.is_zero() {
487 return Err(too_soon(interval));
488 }
489 let out = now
490 .iter()
491 .map(|c| {
492 let current = c.as_totals();
493 let earlier = self
494 .interfaces
495 .iter()
496 .find(|e| e.interface == c.interface)
497 .map_or(current, Counters::as_totals);
498 InterfaceTraffic {
499 interface: c.interface.clone(),
500 traffic: current.since(&earlier, interval),
501 }
502 })
503 .collect();
504 self.interfaces = now;
505 self.interfaces_at = at;
506 Ok(out)
507 }
508}
509
510fn too_soon(elapsed: Duration) -> Error {
511 Error::TooSoon {
512 elapsed,
513 minimum: Duration::from_millis(1),
514 }
515}
516
517#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
520#[non_exhaustive]
521pub struct Connections {
522 pub tcp_established: Option<u64>,
524 pub tcp_time_wait: Option<u64>,
526 pub tcp_total: Option<u64>,
528 pub udp: Option<u64>,
530}
531
532pub fn connections() -> Result<Connections> {
547 crate::sys::connections()
548}
549
550#[cfg(test)]
551mod tests {
552 use std::net::{Ipv4Addr, Ipv6Addr};
553
554 use super::*;
555
556 #[test]
557 fn test_net_mac_display_and_kind() {
558 let m = Mac::from_bytes([0x00, 0x1b, 0x21, 0xaa, 0xbb, 0x0c]);
559 assert_eq!(m.to_string(), "00:1b:21:aa:bb:0c");
560 assert_eq!(m.kind, MacKind::Permanent);
561 assert_eq!(Mac::from_bytes([0x02, 0, 0, 0, 0, 1]).kind, MacKind::Random);
562 let n = IpNet {
563 addr: IpAddr::V4(Ipv4Addr::new(192, 168, 1, 20)),
564 prefix: 24,
565 };
566 assert_eq!(n.to_string(), "192.168.1.20/24");
567 assert!(is_link_local(&IpAddr::V6(Ipv6Addr::new(
568 0xfe80, 0, 0, 0, 0, 0, 0, 1
569 ))));
570 assert!(!is_link_local(&IpAddr::V6(Ipv6Addr::new(
571 0x2001, 0xdb8, 0, 0, 0, 0, 0, 1
572 ))));
573 }
574
575 #[test]
576 fn test_net_traffic_and_backwards_counters() {
577 let c = |rx: u64, tx: u64, prx: u64| Counters {
578 interface: "eth0".to_owned(),
579 received: Bytes::new(rx),
580 sent: Bytes::new(tx),
581 packets_received: prx,
582 packets_sent: 0,
583 errors_in: 1,
584 errors_out: 2,
585 dropped_in: 3,
586 dropped_out: 4,
587 };
588 let a = c(1_000_000, 0, 100).as_totals();
589 let b = c(2_000_000, 500_000, 300).as_totals();
590 assert_eq!((b.errors, b.dropped), (3, 7));
591 let t = b.since(&a, Duration::from_secs(2));
592 assert_eq!(t.download.bytes_per_sec(), 500_000);
593 assert_eq!(t.upload.bytes_per_sec(), 250_000);
594 assert!((t.packets_in_per_sec - 100.0).abs() < 1e-9);
595 let back = a.since(&b, Duration::from_secs(1));
596 assert_eq!((back.download, back.upload), (Rate::ZERO, Rate::ZERO));
597 }
598
599 #[test]
600 fn test_net_live_readings() {
601 let list = interfaces().unwrap();
602 assert!(
603 list.windows(2)
604 .all(|w| (w[0].index, &w[0].name) <= (w[1].index, &w[1].name))
605 );
606 for i in &list {
607 assert!(!i.name.is_empty());
608 }
609 let up = interfaces_with(InterfaceOptions {
610 include_down: false,
611 include_loopback: false,
612 details: false,
613 ..InterfaceOptions::default()
614 })
615 .unwrap();
616 assert!(up.iter().all(|i| i.up && i.kind != InterfaceKind::Loopback));
617 for a in addresses().unwrap() {
618 assert!(!a.is_loopback() && !is_link_local(&a));
619 }
620 let t = totals().unwrap();
621 let _ = (t.received, t.sent);
622 let _ = connections().unwrap();
623 }
624}