1use core::{fmt, time::Duration};
17use std::{net::IpAddr, time::Instant};
18
19use crate::{Bytes, Error, Rate, Result, origin::Origin};
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 primary() -> Result<Option<Interface>> {
210 let Some(index) = crate::sys::primary_interface()? else {
211 return Ok(None);
212 };
213 Ok(interfaces()?.into_iter().find(|i| i.index == index))
214}
215
216#[derive(Clone, Debug, Default, PartialEq, Eq)]
219#[non_exhaustive]
220pub struct Dns {
221 pub servers: Vec<IpAddr>,
223 pub upstream: Vec<IpAddr>,
226 pub search: Vec<String>,
228}
229
230pub fn dns() -> Result<Dns> {
241 crate::sys::dns()
242}
243
244pub fn addresses() -> Result<Vec<IpAddr>> {
256 let options = InterfaceOptions {
257 include_down: false,
258 include_loopback: false,
259 details: false,
260 ..InterfaceOptions::default()
261 };
262 let mut out: Vec<IpAddr> = interfaces_with(options)?
263 .into_iter()
264 .flat_map(|i| i.addresses)
265 .map(|n| n.addr)
266 .filter(|a| !a.is_loopback() && !is_link_local(a))
267 .collect();
268 out.dedup();
269 Ok(out)
270}
271
272fn is_link_local(addr: &IpAddr) -> bool {
273 match addr {
274 IpAddr::V4(v4) => v4.is_link_local(),
275 IpAddr::V6(v6) => (v6.segments()[0] & 0xffc0) == 0xfe80,
276 }
277}
278
279#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
281#[non_exhaustive]
282pub struct Totals {
283 pub received: Bytes,
285 pub sent: Bytes,
287 pub packets_received: u64,
289 pub packets_sent: u64,
291 pub errors: u64,
293 pub dropped: u64,
295}
296
297#[derive(Clone, Copy, PartialEq, Debug)]
299#[non_exhaustive]
300pub struct Traffic {
301 pub download: Rate,
303 pub upload: Rate,
305 pub packets_in_per_sec: f64,
307 pub packets_out_per_sec: f64,
309 pub interval: Duration,
311}
312
313#[derive(Clone, Debug, PartialEq)]
315#[non_exhaustive]
316pub struct InterfaceTraffic {
317 pub interface: String,
319 pub traffic: Traffic,
321}
322
323#[derive(Clone, Debug, PartialEq, Eq)]
325#[non_exhaustive]
326pub struct Counters {
327 pub interface: String,
329 pub received: Bytes,
331 pub sent: Bytes,
333 pub packets_received: u64,
335 pub packets_sent: u64,
337 pub errors_in: u64,
339 pub errors_out: u64,
341 pub dropped_in: u64,
343 pub dropped_out: u64,
345}
346
347impl Totals {
348 #[allow(dead_code)] pub(crate) fn add(&mut self, c: &Counters) {
351 self.received = self.received.saturating_add(c.received);
352 self.sent = self.sent.saturating_add(c.sent);
353 self.packets_received = self.packets_received.saturating_add(c.packets_received);
354 self.packets_sent = self.packets_sent.saturating_add(c.packets_sent);
355 self.errors = self
356 .errors
357 .saturating_add(c.errors_in)
358 .saturating_add(c.errors_out);
359 self.dropped = self
360 .dropped
361 .saturating_add(c.dropped_in)
362 .saturating_add(c.dropped_out);
363 }
364
365 fn since(&self, earlier: &Totals, interval: Duration) -> Traffic {
368 let d = |new: u64, old: u64| new.saturating_sub(old);
369 let secs = interval.as_secs_f64();
370 let per_sec = |n: u64| if secs > 0.0 { n as f64 / secs } else { 0.0 };
371 Traffic {
372 download: Rate::from_delta(d(self.received.raw(), earlier.received.raw()), interval),
373 upload: Rate::from_delta(d(self.sent.raw(), earlier.sent.raw()), interval),
374 packets_in_per_sec: per_sec(d(self.packets_received, earlier.packets_received)),
375 packets_out_per_sec: per_sec(d(self.packets_sent, earlier.packets_sent)),
376 interval,
377 }
378 }
379}
380
381impl Counters {
382 fn as_totals(&self) -> Totals {
383 let mut t = Totals::default();
384 t.add(self);
385 t
386 }
387}
388
389pub const DEFAULT_WINDOW: Duration = Duration::from_secs(1);
391
392const MIN_WINDOW: Duration = Duration::from_millis(100);
393const MAX_WINDOW: Duration = Duration::from_secs(60);
394
395pub fn totals() -> Result<Totals> {
409 crate::sys::net_totals()
410}
411
412pub fn counters() -> Result<Vec<Counters>> {
418 crate::sys::net_counters()
419}
420
421pub fn traffic() -> Result<Traffic> {
435 traffic_over(DEFAULT_WINDOW)
436}
437
438pub fn traffic_over(window: Duration) -> Result<Traffic> {
445 let mut sampler = Sampler::totals_only()?;
446 std::thread::sleep(window.clamp(MIN_WINDOW, MAX_WINDOW));
447 sampler.sample()
448}
449
450#[derive(Debug)]
469pub struct Sampler {
470 total: Totals,
471 at: Instant,
472 interfaces: Vec<Counters>,
473 interfaces_at: Instant,
474 origin: Origin,
475}
476
477impl Sampler {
478 pub fn new() -> Result<Sampler> {
484 Self::from(Origin::local())
485 }
486
487 pub(crate) fn from(origin: Origin) -> Result<Sampler> {
489 let now = Instant::now();
490 Ok(Sampler {
491 total: origin.net_totals()?,
492 at: now,
493 interfaces: origin.net_counters()?,
494 interfaces_at: now,
495 origin,
496 })
497 }
498
499 fn totals_only() -> Result<Sampler> {
500 let now = Instant::now();
501 Ok(Sampler {
502 total: totals()?,
503 at: now,
504 interfaces: Vec::new(),
505 interfaces_at: now,
506 origin: Origin::local(),
507 })
508 }
509
510 pub fn sample(&mut self) -> Result<Traffic> {
518 let now = self.origin.net_totals()?;
519 let at = Instant::now();
520 let interval = at.duration_since(self.at);
521 if interval.is_zero() {
522 return Err(too_soon(interval));
523 }
524 let traffic = now.since(&self.total, interval);
525 self.total = now;
526 self.at = at;
527 Ok(traffic)
528 }
529
530 pub fn sample_per_interface(&mut self) -> Result<Vec<InterfaceTraffic>> {
538 let now = self.origin.net_counters()?;
539 let at = Instant::now();
540 let interval = at.duration_since(self.interfaces_at);
541 if interval.is_zero() {
542 return Err(too_soon(interval));
543 }
544 let out = now
545 .iter()
546 .map(|c| {
547 let current = c.as_totals();
548 let earlier = self
549 .interfaces
550 .iter()
551 .find(|e| e.interface == c.interface)
552 .map_or(current, Counters::as_totals);
553 InterfaceTraffic {
554 interface: c.interface.clone(),
555 traffic: current.since(&earlier, interval),
556 }
557 })
558 .collect();
559 self.interfaces = now;
560 self.interfaces_at = at;
561 Ok(out)
562 }
563}
564
565fn too_soon(elapsed: Duration) -> Error {
566 Error::TooSoon {
567 elapsed,
568 minimum: Duration::from_millis(1),
569 }
570}
571
572#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
575#[non_exhaustive]
576pub struct Connections {
577 pub tcp_established: Option<u64>,
579 pub tcp_time_wait: Option<u64>,
581 pub tcp_total: Option<u64>,
583 pub udp: Option<u64>,
585}
586
587pub fn connections() -> Result<Connections> {
602 crate::sys::connections()
603}
604
605#[cfg(test)]
606mod tests {
607 use std::net::{Ipv4Addr, Ipv6Addr};
608
609 use super::*;
610
611 #[test]
612 fn test_net_mac_display_and_kind() {
613 let m = Mac::from_bytes([0x00, 0x1b, 0x21, 0xaa, 0xbb, 0x0c]);
614 assert_eq!(m.to_string(), "00:1b:21:aa:bb:0c");
615 assert_eq!(m.kind, MacKind::Permanent);
616 assert_eq!(Mac::from_bytes([0x02, 0, 0, 0, 0, 1]).kind, MacKind::Random);
617 let n = IpNet {
618 addr: IpAddr::V4(Ipv4Addr::new(192, 168, 1, 20)),
619 prefix: 24,
620 };
621 assert_eq!(n.to_string(), "192.168.1.20/24");
622 assert!(is_link_local(&IpAddr::V6(Ipv6Addr::new(
623 0xfe80, 0, 0, 0, 0, 0, 0, 1
624 ))));
625 assert!(!is_link_local(&IpAddr::V6(Ipv6Addr::new(
626 0x2001, 0xdb8, 0, 0, 0, 0, 0, 1
627 ))));
628 }
629
630 #[test]
631 fn test_net_traffic_and_backwards_counters() {
632 let c = |rx: u64, tx: u64, prx: u64| Counters {
633 interface: "eth0".to_owned(),
634 received: Bytes::new(rx),
635 sent: Bytes::new(tx),
636 packets_received: prx,
637 packets_sent: 0,
638 errors_in: 1,
639 errors_out: 2,
640 dropped_in: 3,
641 dropped_out: 4,
642 };
643 let a = c(1_000_000, 0, 100).as_totals();
644 let b = c(2_000_000, 500_000, 300).as_totals();
645 assert_eq!((b.errors, b.dropped), (3, 7));
646 let t = b.since(&a, Duration::from_secs(2));
647 assert_eq!(t.download.bytes_per_sec(), 500_000);
648 assert_eq!(t.upload.bytes_per_sec(), 250_000);
649 assert!((t.packets_in_per_sec - 100.0).abs() < 1e-9);
650 let back = a.since(&b, Duration::from_secs(1));
651 assert_eq!((back.download, back.upload), (Rate::ZERO, Rate::ZERO));
652 }
653
654 #[test]
655 fn test_net_live_readings() {
656 let list = interfaces().unwrap();
657 assert!(
658 list.windows(2)
659 .all(|w| (w[0].index, &w[0].name) <= (w[1].index, &w[1].name))
660 );
661 for i in &list {
662 assert!(!i.name.is_empty());
663 }
664 let up = interfaces_with(InterfaceOptions {
665 include_down: false,
666 include_loopback: false,
667 details: false,
668 ..InterfaceOptions::default()
669 })
670 .unwrap();
671 assert!(up.iter().all(|i| i.up && i.kind != InterfaceKind::Loopback));
672 for a in addresses().unwrap() {
673 assert!(!a.is_loopback() && !is_link_local(&a));
674 }
675 let t = totals().unwrap();
676 let _ = (t.received, t.sent);
677 let _ = connections().unwrap();
678 }
679}