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};
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 addresses of the interfaces that are up, without loopback and
198/// link-local addresses (E-57).
199///
200/// ```
201/// println!("addresses: {:?}", sys_lib::net::addresses()?);
202/// # Ok::<(), sys_lib::Error>(())
203/// ```
204///
205/// # Errors
206///
207/// As [`interfaces`].
208pub 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/// Bytes and packets moved since boot, every interface but loopback.
233#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
234#[non_exhaustive]
235pub struct Totals {
236    /// Bytes received.
237    pub received: Bytes,
238    /// Bytes sent.
239    pub sent: Bytes,
240    /// Packets received.
241    pub packets_received: u64,
242    /// Packets sent.
243    pub packets_sent: u64,
244    /// Errors, both directions.
245    pub errors: u64,
246    /// Packets dropped, both directions.
247    pub dropped: u64,
248}
249
250/// Download and upload over an interval.
251#[derive(Clone, Copy, PartialEq, Debug)]
252#[non_exhaustive]
253pub struct Traffic {
254    /// Bytes received per second.
255    pub download: Rate,
256    /// Bytes sent per second.
257    pub upload: Rate,
258    /// Packets received per second.
259    pub packets_in_per_sec: f64,
260    /// Packets sent per second.
261    pub packets_out_per_sec: f64,
262    /// The time the values cover.
263    pub interval: Duration,
264}
265
266/// One interface's traffic.
267#[derive(Clone, Debug, PartialEq)]
268#[non_exhaustive]
269pub struct InterfaceTraffic {
270    /// The interface's name.
271    pub interface: String,
272    /// Its traffic.
273    pub traffic: Traffic,
274}
275
276/// One interface's cumulative counters.
277#[derive(Clone, Debug, PartialEq, Eq)]
278#[non_exhaustive]
279pub struct Counters {
280    /// The interface's name.
281    pub interface: String,
282    /// Bytes received.
283    pub received: Bytes,
284    /// Bytes sent.
285    pub sent: Bytes,
286    /// Packets received.
287    pub packets_received: u64,
288    /// Packets sent.
289    pub packets_sent: u64,
290    /// Receive errors.
291    pub errors_in: u64,
292    /// Transmit errors.
293    pub errors_out: u64,
294    /// Received packets dropped.
295    pub dropped_in: u64,
296    /// Packets dropped before sending.
297    pub dropped_out: u64,
298}
299
300impl Totals {
301    /// Adds one interface's counters (for a backend that has only those).
302    #[allow(dead_code)] // the macOS and Windows backends
303    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    /// The traffic between `earlier` and `self`; a counter that went backwards
319    /// (an interface re-created, a driver reset) counts as no traffic.
320    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
342/// The interval [`traffic`] measures over: 1 s.
343pub 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
348/// Bytes and packets moved since boot, every interface but loopback: one
349/// read, no waiting. Counters are 64-bit on every platform. Inside a container
350/// they are the container's network namespace.
351///
352/// ```
353/// let total = sys_lib::net::totals()?;
354/// println!("since boot: {} received, {} sent", total.received, total.sent);
355/// # Ok::<(), sys_lib::Error>(())
356/// ```
357///
358/// # Errors
359///
360/// `NotFound` when the counters are hidden; `Malformed`; `Os`.
361pub fn totals() -> Result<Totals> {
362    crate::sys::net_totals()
363}
364
365/// Each interface's cumulative counters, loopback included (Tier 2).
366///
367/// # Errors
368///
369/// As [`totals`].
370pub fn counters() -> Result<Vec<Counters>> {
371    crate::sys::net_counters()
372}
373
374/// Download and upload over the next second. **Blocks for
375/// [`DEFAULT_WINDOW`]**; a monitor keeps a [`Sampler`].
376///
377/// ```
378/// let t = sys_lib::net::traffic()?;            // blocks 1 s
379/// println!("down {} up {}", t.download, t.upload);
380/// println!("down {}", t.download.bits());
381/// # Ok::<(), sys_lib::Error>(())
382/// ```
383///
384/// # Errors
385///
386/// As [`Sampler::sample`].
387pub fn traffic() -> Result<Traffic> {
388    traffic_over(DEFAULT_WINDOW)
389}
390
391/// Download and upload over `window`, clamped to 100 ms ..= 60 s. **Blocks for
392/// the window.**
393///
394/// # Errors
395///
396/// As [`Sampler::sample`].
397pub 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/// Measures download and upload between samples. Owned by the caller: two
404/// samplers never disturb each other. `sample` never blocks and allocates
405/// nothing.
406///
407/// ```no_run
408/// use std::time::Duration;
409///
410/// let mut net = sys_lib::net::Sampler::new()?;
411/// loop {
412///     std::thread::sleep(Duration::from_secs(5));
413///     let t = net.sample()?;
414///     println!("down {} up {}", t.download, t.upload);
415///     for i in net.sample_per_interface()? {
416///         println!("  {}: down {} up {}", i.interface, i.traffic.download, i.traffic.upload);
417///     }
418/// }
419/// # Ok::<(), sys_lib::Error>(())
420/// ```
421#[derive(Debug)]
422pub struct Sampler {
423    total: Totals,
424    at: Instant,
425    interfaces: Vec<Counters>,
426    interfaces_at: Instant,
427}
428
429impl Sampler {
430    /// Takes the first reading, of the totals and of each interface.
431    ///
432    /// # Errors
433    ///
434    /// As [`totals`].
435    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    /// Download and upload since the previous sample, every interface but
456    /// loopback. A counter that went backwards re-bases the sampler and reads
457    /// as no traffic for that interval.
458    ///
459    /// # Errors
460    ///
461    /// `TooSoon` when no time passed since the previous sample.
462    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    /// Traffic since the previous per-interface sample, for each interface
476    /// (allocates the `Vec`). An interface seen for the first time reads as no
477    /// traffic.
478    ///
479    /// # Errors
480    ///
481    /// `TooSoon` when no time passed since the previous sample.
482    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/// How many network connections the machine has open, as counts. A value an
518/// OS does not report is `None`.
519#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
520#[non_exhaustive]
521pub struct Connections {
522    /// Open TCP connections.
523    pub tcp_established: Option<u64>,
524    /// Closed TCP connections waiting out the TIME_WAIT period.
525    pub tcp_time_wait: Option<u64>,
526    /// Every TCP socket, listening ones included.
527    pub tcp_total: Option<u64>,
528    /// UDP sockets.
529    pub udp: Option<u64>,
530}
531
532/// How many network connections the machine has open: counts only, never
533/// addresses, ports, or owners. Inside a container they are the container's
534/// network namespace.
535///
536/// ```
537/// if let Some(open) = sys_lib::net::connections()?.tcp_established {
538///     println!("{open} TCP connections open");
539/// }
540/// # Ok::<(), sys_lib::Error>(())
541/// ```
542///
543/// # Errors
544///
545/// `NotFound` when the counters are hidden; `Malformed`; `Os`.
546pub 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}