sys_lib/net.rs
1//! Network interfaces, download and upload, and connection counts.
2//!
3//! sys-lib never sends a packet, never lists connections or their addresses,
4//! and never says which program owns a socket: it reports interfaces and
5//! counts.
6//!
7//! ```
8//! use sys_lib as sys;
9//!
10//! for i in sys::net::interfaces()? {
11//! println!("{} {:?} up={} speed={:?}", i.name, i.kind, i.running, i.speed_mbps);
12//! }
13//! # Ok::<(), sys_lib::Error>(())
14//! ```
15
16use core::{fmt, time::Duration};
17use std::{net::IpAddr, time::Instant};
18
19use crate::{Bytes, Error, Rate, Result};
20
21/// One network interface.
22#[derive(Clone, Debug, PartialEq, Eq)]
23#[non_exhaustive]
24pub struct Interface {
25 /// The name: `eth0`, `en0`, `Ethernet 2` (UTF-8; converted lossily).
26 pub name: String,
27 /// The OS's interface index.
28 pub index: u32,
29 /// The friendly description (Windows).
30 pub description: Option<String>,
31 /// What kind of interface it is.
32 pub kind: InterfaceKind,
33 /// The hardware address, when it has one (E-53).
34 pub mac: Option<Mac>,
35 /// The addresses with their prefix lengths.
36 pub addresses: Vec<IpNet>,
37 /// Administratively up.
38 pub up: bool,
39 /// Link up, operational.
40 pub running: bool,
41 /// The MTU, when reported (and `details` was set).
42 pub mtu: Option<u32>,
43 /// The link speed in megabits per second, when the driver reports it (E-58).
44 pub speed_mbps: Option<u64>,
45 /// Backed by hardware, rather than a virtual or tunnel interface.
46 pub is_physical: bool,
47}
48
49/// What kind of network interface.
50#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
51#[non_exhaustive]
52pub enum InterfaceKind {
53 /// Wired Ethernet.
54 Ethernet,
55 /// Wi-Fi.
56 Wifi,
57 /// Loopback.
58 Loopback,
59 /// A tunnel (WireGuard, `tun`, GRE, IP-in-IP).
60 Tunnel,
61 /// A bridge.
62 Bridge,
63 /// Virtual (`veth`, a VM's adapter, a bond member).
64 Virtual,
65 /// Mobile broadband.
66 Cellular,
67 /// Anything else.
68 Other,
69}
70
71/// A hardware (MAC) address. An identifier: for device identity use the
72/// `device` module (0.5), never a raw MAC.
73#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
74#[non_exhaustive]
75pub struct Mac {
76 /// The six bytes.
77 pub bytes: [u8; 6],
78 /// Whether the address is the hardware's own or randomized.
79 pub kind: MacKind,
80}
81
82impl Mac {
83 /// A MAC whose kind comes from the locally administered bit, for an OS
84 /// that keeps no assignment type.
85 #[allow(dead_code)] // the macOS and Windows backends
86 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 /// `aa:bb:cc:dd:ee:ff`.
98 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/// Whether a MAC address is the hardware's own (E-54).
109#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
110#[non_exhaustive]
111pub enum MacKind {
112 /// The hardware's burned-in address.
113 Permanent,
114 /// Randomized (Wi-Fi privacy addresses, Android, Windows, NetworkManager).
115 Random,
116 /// Not known (Linux: an address stolen from another device or set by hand).
117 Unknown,
118}
119
120/// An address with its prefix length.
121#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
122pub struct IpNet {
123 /// The address.
124 pub addr: IpAddr,
125 /// The prefix length in bits.
126 pub prefix: u8,
127}
128
129impl fmt::Display for IpNet {
130 /// `192.168.1.20/24`, `fe80::1/64`.
131 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
132 write!(f, "{}/{}", self.addr, self.prefix)
133 }
134}
135
136/// Which interfaces [`interfaces_with`] returns, and in how much detail.
137#[derive(Clone, Copy, Debug)]
138#[non_exhaustive]
139pub struct InterfaceOptions {
140 /// Include interfaces that are down (default true).
141 pub include_down: bool,
142 /// Include loopback (default true).
143 pub include_loopback: bool,
144 /// Read the per-interface details: speed, MTU, kind (default true; false
145 /// skips the per-interface `/sys` reads on Linux).
146 pub details: bool,
147 /// The most interfaces read; more is `TooLarge` (default 4 096).
148 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
162/// Every network interface, sorted by index, then name.
163///
164/// ```
165/// for i in sys_lib::net::interfaces()? {
166/// let mac = i.mac.map(|m| format!("{m} ({:?})", m.kind)).unwrap_or_default();
167/// println!("{} {:?} up={} {mac}", i.name, i.kind, i.running);
168/// for a in &i.addresses { println!(" {a}"); }
169/// }
170/// # Ok::<(), sys_lib::Error>(())
171/// ```
172///
173/// # Errors
174///
175/// `TooLarge` with more than 4 096 interfaces; `Os` when the OS call fails.
176pub fn interfaces() -> Result<Vec<Interface>> {
177 interfaces_with(InterfaceOptions::default())
178}
179
180/// The interfaces `options` selects, sorted by index, then name. A Kubernetes
181/// node with thousands of `veth` interfaces lists them quickly with
182/// `details: false` (E-56).
183///
184/// # Errors
185///
186/// As [`interfaces`], with `options.max_interfaces` as the budget.
187pub 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
197/// The interface holding the default route; `None` without one.
198///
199/// ```
200/// if let Some(i) = sys_lib::net::primary()? {
201/// println!("{} {:?}", i.name, i.addresses);
202/// }
203/// # Ok::<(), sys_lib::Error>(())
204/// ```
205///
206/// # Errors
207///
208/// As [`interfaces`].
209pub 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/// The DNS configuration, read from configuration only: sys-lib never sends a
217/// DNS query.
218#[derive(Clone, Debug, Default, PartialEq, Eq)]
219#[non_exhaustive]
220pub struct Dns {
221 /// What the system resolver uses.
222 pub servers: Vec<IpAddr>,
223 /// Behind a local stub (systemd-resolved at 127.0.0.53), the servers it
224 /// forwards to.
225 pub upstream: Vec<IpAddr>,
226 /// The search domains.
227 pub search: Vec<String>,
228}
229
230/// The DNS servers this machine is configured to use.
231///
232/// ```
233/// println!("{:?}", sys_lib::net::dns().map(|d| d.servers));
234/// ```
235///
236/// # Errors
237///
238/// `TooLarge` past 64 servers or 64 search domains; `NotFound` without a
239/// resolver configuration; `Unsupported` where the OS has none to read.
240pub fn dns() -> Result<Dns> {
241 crate::sys::dns()
242}
243
244/// The addresses of the interfaces that are up, without loopback and
245/// link-local addresses (E-57).
246///
247/// ```
248/// println!("addresses: {:?}", sys_lib::net::addresses()?);
249/// # Ok::<(), sys_lib::Error>(())
250/// ```
251///
252/// # Errors
253///
254/// As [`interfaces`].
255pub 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/// Bytes and packets moved since boot, every interface but loopback.
280#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
281#[non_exhaustive]
282pub struct Totals {
283 /// Bytes received.
284 pub received: Bytes,
285 /// Bytes sent.
286 pub sent: Bytes,
287 /// Packets received.
288 pub packets_received: u64,
289 /// Packets sent.
290 pub packets_sent: u64,
291 /// Errors, both directions.
292 pub errors: u64,
293 /// Packets dropped, both directions.
294 pub dropped: u64,
295}
296
297/// Download and upload over an interval.
298#[derive(Clone, Copy, PartialEq, Debug)]
299#[non_exhaustive]
300pub struct Traffic {
301 /// Bytes received per second.
302 pub download: Rate,
303 /// Bytes sent per second.
304 pub upload: Rate,
305 /// Packets received per second.
306 pub packets_in_per_sec: f64,
307 /// Packets sent per second.
308 pub packets_out_per_sec: f64,
309 /// The time the values cover.
310 pub interval: Duration,
311}
312
313/// One interface's traffic.
314#[derive(Clone, Debug, PartialEq)]
315#[non_exhaustive]
316pub struct InterfaceTraffic {
317 /// The interface's name.
318 pub interface: String,
319 /// Its traffic.
320 pub traffic: Traffic,
321}
322
323/// One interface's cumulative counters.
324#[derive(Clone, Debug, PartialEq, Eq)]
325#[non_exhaustive]
326pub struct Counters {
327 /// The interface's name.
328 pub interface: String,
329 /// Bytes received.
330 pub received: Bytes,
331 /// Bytes sent.
332 pub sent: Bytes,
333 /// Packets received.
334 pub packets_received: u64,
335 /// Packets sent.
336 pub packets_sent: u64,
337 /// Receive errors.
338 pub errors_in: u64,
339 /// Transmit errors.
340 pub errors_out: u64,
341 /// Received packets dropped.
342 pub dropped_in: u64,
343 /// Packets dropped before sending.
344 pub dropped_out: u64,
345}
346
347impl Totals {
348 /// Adds one interface's counters (for a backend that has only those).
349 #[allow(dead_code)] // the macOS and Windows backends
350 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 /// The traffic between `earlier` and `self`; a counter that went backwards
366 /// (an interface re-created, a driver reset) counts as no traffic.
367 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
389/// The interval [`traffic`] measures over: 1 s.
390pub 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
395/// Bytes and packets moved since boot, every interface but loopback: one
396/// read, no waiting. Counters are 64-bit on every platform. Inside a container
397/// they are the container's network namespace.
398///
399/// ```
400/// let total = sys_lib::net::totals()?;
401/// println!("since boot: {} received, {} sent", total.received, total.sent);
402/// # Ok::<(), sys_lib::Error>(())
403/// ```
404///
405/// # Errors
406///
407/// `NotFound` when the counters are hidden; `Malformed`; `Os`.
408pub fn totals() -> Result<Totals> {
409 crate::sys::net_totals()
410}
411
412/// Each interface's cumulative counters, loopback included (Tier 2).
413///
414/// # Errors
415///
416/// As [`totals`].
417pub fn counters() -> Result<Vec<Counters>> {
418 crate::sys::net_counters()
419}
420
421/// Download and upload over the next second. **Blocks for
422/// [`DEFAULT_WINDOW`]**; a monitor keeps a [`Sampler`].
423///
424/// ```
425/// let t = sys_lib::net::traffic()?; // blocks 1 s
426/// println!("down {} up {}", t.download, t.upload);
427/// println!("down {}", t.download.bits());
428/// # Ok::<(), sys_lib::Error>(())
429/// ```
430///
431/// # Errors
432///
433/// As [`Sampler::sample`].
434pub fn traffic() -> Result<Traffic> {
435 traffic_over(DEFAULT_WINDOW)
436}
437
438/// Download and upload over `window`, clamped to 100 ms ..= 60 s. **Blocks for
439/// the window.**
440///
441/// # Errors
442///
443/// As [`Sampler::sample`].
444pub 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/// Measures download and upload between samples. Owned by the caller: two
451/// samplers never disturb each other. `sample` never blocks and allocates
452/// nothing.
453///
454/// ```no_run
455/// use std::time::Duration;
456///
457/// let mut net = sys_lib::net::Sampler::new()?;
458/// loop {
459/// std::thread::sleep(Duration::from_secs(5));
460/// let t = net.sample()?;
461/// println!("down {} up {}", t.download, t.upload);
462/// for i in net.sample_per_interface()? {
463/// println!(" {}: down {} up {}", i.interface, i.traffic.download, i.traffic.upload);
464/// }
465/// }
466/// # Ok::<(), sys_lib::Error>(())
467/// ```
468#[derive(Debug)]
469pub struct Sampler {
470 total: Totals,
471 at: Instant,
472 interfaces: Vec<Counters>,
473 interfaces_at: Instant,
474}
475
476impl Sampler {
477 /// Takes the first reading, of the totals and of each interface.
478 ///
479 /// # Errors
480 ///
481 /// As [`totals`].
482 pub fn new() -> Result<Sampler> {
483 let now = Instant::now();
484 Ok(Sampler {
485 total: totals()?,
486 at: now,
487 interfaces: counters()?,
488 interfaces_at: now,
489 })
490 }
491
492 fn totals_only() -> Result<Sampler> {
493 let now = Instant::now();
494 Ok(Sampler {
495 total: totals()?,
496 at: now,
497 interfaces: Vec::new(),
498 interfaces_at: now,
499 })
500 }
501
502 /// Download and upload since the previous sample, every interface but
503 /// loopback. A counter that went backwards re-bases the sampler and reads
504 /// as no traffic for that interval.
505 ///
506 /// # Errors
507 ///
508 /// `TooSoon` when no time passed since the previous sample.
509 pub fn sample(&mut self) -> Result<Traffic> {
510 let now = totals()?;
511 let at = Instant::now();
512 let interval = at.duration_since(self.at);
513 if interval.is_zero() {
514 return Err(too_soon(interval));
515 }
516 let traffic = now.since(&self.total, interval);
517 self.total = now;
518 self.at = at;
519 Ok(traffic)
520 }
521
522 /// Traffic since the previous per-interface sample, for each interface
523 /// (allocates the `Vec`). An interface seen for the first time reads as no
524 /// traffic.
525 ///
526 /// # Errors
527 ///
528 /// `TooSoon` when no time passed since the previous sample.
529 pub fn sample_per_interface(&mut self) -> Result<Vec<InterfaceTraffic>> {
530 let now = counters()?;
531 let at = Instant::now();
532 let interval = at.duration_since(self.interfaces_at);
533 if interval.is_zero() {
534 return Err(too_soon(interval));
535 }
536 let out = now
537 .iter()
538 .map(|c| {
539 let current = c.as_totals();
540 let earlier = self
541 .interfaces
542 .iter()
543 .find(|e| e.interface == c.interface)
544 .map_or(current, Counters::as_totals);
545 InterfaceTraffic {
546 interface: c.interface.clone(),
547 traffic: current.since(&earlier, interval),
548 }
549 })
550 .collect();
551 self.interfaces = now;
552 self.interfaces_at = at;
553 Ok(out)
554 }
555}
556
557fn too_soon(elapsed: Duration) -> Error {
558 Error::TooSoon {
559 elapsed,
560 minimum: Duration::from_millis(1),
561 }
562}
563
564/// How many network connections the machine has open, as counts. A value an
565/// OS does not report is `None`.
566#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
567#[non_exhaustive]
568pub struct Connections {
569 /// Open TCP connections.
570 pub tcp_established: Option<u64>,
571 /// Closed TCP connections waiting out the TIME_WAIT period.
572 pub tcp_time_wait: Option<u64>,
573 /// Every TCP socket, listening ones included.
574 pub tcp_total: Option<u64>,
575 /// UDP sockets.
576 pub udp: Option<u64>,
577}
578
579/// How many network connections the machine has open: counts only, never
580/// addresses, ports, or owners. Inside a container they are the container's
581/// network namespace.
582///
583/// ```
584/// if let Some(open) = sys_lib::net::connections()?.tcp_established {
585/// println!("{open} TCP connections open");
586/// }
587/// # Ok::<(), sys_lib::Error>(())
588/// ```
589///
590/// # Errors
591///
592/// `NotFound` when the counters are hidden; `Malformed`; `Os`.
593pub fn connections() -> Result<Connections> {
594 crate::sys::connections()
595}
596
597#[cfg(test)]
598mod tests {
599 use std::net::{Ipv4Addr, Ipv6Addr};
600
601 use super::*;
602
603 #[test]
604 fn test_net_mac_display_and_kind() {
605 let m = Mac::from_bytes([0x00, 0x1b, 0x21, 0xaa, 0xbb, 0x0c]);
606 assert_eq!(m.to_string(), "00:1b:21:aa:bb:0c");
607 assert_eq!(m.kind, MacKind::Permanent);
608 assert_eq!(Mac::from_bytes([0x02, 0, 0, 0, 0, 1]).kind, MacKind::Random);
609 let n = IpNet {
610 addr: IpAddr::V4(Ipv4Addr::new(192, 168, 1, 20)),
611 prefix: 24,
612 };
613 assert_eq!(n.to_string(), "192.168.1.20/24");
614 assert!(is_link_local(&IpAddr::V6(Ipv6Addr::new(
615 0xfe80, 0, 0, 0, 0, 0, 0, 1
616 ))));
617 assert!(!is_link_local(&IpAddr::V6(Ipv6Addr::new(
618 0x2001, 0xdb8, 0, 0, 0, 0, 0, 1
619 ))));
620 }
621
622 #[test]
623 fn test_net_traffic_and_backwards_counters() {
624 let c = |rx: u64, tx: u64, prx: u64| Counters {
625 interface: "eth0".to_owned(),
626 received: Bytes::new(rx),
627 sent: Bytes::new(tx),
628 packets_received: prx,
629 packets_sent: 0,
630 errors_in: 1,
631 errors_out: 2,
632 dropped_in: 3,
633 dropped_out: 4,
634 };
635 let a = c(1_000_000, 0, 100).as_totals();
636 let b = c(2_000_000, 500_000, 300).as_totals();
637 assert_eq!((b.errors, b.dropped), (3, 7));
638 let t = b.since(&a, Duration::from_secs(2));
639 assert_eq!(t.download.bytes_per_sec(), 500_000);
640 assert_eq!(t.upload.bytes_per_sec(), 250_000);
641 assert!((t.packets_in_per_sec - 100.0).abs() < 1e-9);
642 let back = a.since(&b, Duration::from_secs(1));
643 assert_eq!((back.download, back.upload), (Rate::ZERO, Rate::ZERO));
644 }
645
646 #[test]
647 fn test_net_live_readings() {
648 let list = interfaces().unwrap();
649 assert!(
650 list.windows(2)
651 .all(|w| (w[0].index, &w[0].name) <= (w[1].index, &w[1].name))
652 );
653 for i in &list {
654 assert!(!i.name.is_empty());
655 }
656 let up = interfaces_with(InterfaceOptions {
657 include_down: false,
658 include_loopback: false,
659 details: false,
660 ..InterfaceOptions::default()
661 })
662 .unwrap();
663 assert!(up.iter().all(|i| i.up && i.kind != InterfaceKind::Loopback));
664 for a in addresses().unwrap() {
665 assert!(!a.is_loopback() && !is_link_local(&a));
666 }
667 let t = totals().unwrap();
668 let _ = (t.received, t.sent);
669 let _ = connections().unwrap();
670 }
671}