Skip to main content

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, origin::Origin};
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    origin: Origin,
475}
476
477impl Sampler {
478    /// Takes the first reading, of the totals and of each interface.
479    ///
480    /// # Errors
481    ///
482    /// As [`totals`].
483    pub fn new() -> Result<Sampler> {
484        Self::from(Origin::local())
485    }
486
487    /// [`new`](Sampler::new), reading from `origin`.
488    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    /// Download and upload since the previous sample, every interface but
511    /// loopback. A counter that went backwards re-bases the sampler and reads
512    /// as no traffic for that interval.
513    ///
514    /// # Errors
515    ///
516    /// `TooSoon` when no time passed since the previous sample.
517    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    /// Traffic since the previous per-interface sample, for each interface
531    /// (allocates the `Vec`). An interface seen for the first time reads as no
532    /// traffic.
533    ///
534    /// # Errors
535    ///
536    /// `TooSoon` when no time passed since the previous sample.
537    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/// How many network connections the machine has open, as counts. A value an
573/// OS does not report is `None`.
574#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
575#[non_exhaustive]
576pub struct Connections {
577    /// Open TCP connections.
578    pub tcp_established: Option<u64>,
579    /// Closed TCP connections waiting out the TIME_WAIT period.
580    pub tcp_time_wait: Option<u64>,
581    /// Every TCP socket, listening ones included.
582    pub tcp_total: Option<u64>,
583    /// UDP sockets.
584    pub udp: Option<u64>,
585}
586
587/// How many network connections the machine has open: counts only, never
588/// addresses, ports, or owners. Inside a container they are the container's
589/// network namespace.
590///
591/// ```
592/// if let Some(open) = sys_lib::net::connections()?.tcp_established {
593///     println!("{open} TCP connections open");
594/// }
595/// # Ok::<(), sys_lib::Error>(())
596/// ```
597///
598/// # Errors
599///
600/// `NotFound` when the counters are hidden; `Malformed`; `Os`.
601pub 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}