Skip to main content

nmbrs_runtime/sysmon/
net.rs

1// Copyright 2024-2026 Jonathan Shook
2// SPDX-License-Identifier: Apache-2.0
3
4//! Network throughput per interface, from `/proc/net/dev`
5//! (SRD-118 ยง3.6).
6
7/// One interface's cumulative byte counters.
8#[derive(Debug, Clone, PartialEq, Eq)]
9pub struct NetCounters {
10    pub iface: String,
11    pub rx_bytes: u64,
12    pub tx_bytes: u64,
13}
14
15/// Every interface's cumulative counters but the loopback's. A line
16/// is `iface: <8 receive fields> <8 transmit fields>`; bytes are the
17/// first field of each half.
18pub fn parse_net_dev(text: &str) -> Vec<NetCounters> {
19    text.lines()
20        .filter_map(|line| {
21            let (iface, counters) = line.split_once(':')?;
22            let iface = iface.trim();
23            if iface == "lo" {
24                return None;
25            }
26            let fields: Vec<&str> = counters.split_whitespace().collect();
27            Some(NetCounters {
28                iface: iface.to_string(),
29                rx_bytes: fields.first()?.parse().ok()?,
30                tx_bytes: fields.get(8)?.parse().ok()?,
31            })
32        })
33        .collect()
34}
35
36/// What one interface received and sent over a sample window.
37#[derive(Debug, Clone, PartialEq)]
38pub struct NetRate {
39    pub iface: String,
40    pub rx_bytes_per_s: f64,
41    pub tx_bytes_per_s: f64,
42}
43
44/// Each interface's throughput between two snapshots `dt_s` apart, for
45/// the interfaces in both. An interface that has never carried a byte
46/// is left out, so an unused one makes no series.
47pub fn net_rates(prev: &[NetCounters], cur: &[NetCounters], dt_s: f64) -> Vec<NetRate> {
48    if dt_s <= 0.0 {
49        return Vec::new();
50    }
51    cur.iter()
52        .filter(|now| now.rx_bytes > 0 || now.tx_bytes > 0)
53        .filter_map(|now| {
54            let before = prev.iter().find(|n| n.iface == now.iface)?;
55            Some(NetRate {
56                iface: now.iface.clone(),
57                rx_bytes_per_s: now.rx_bytes.saturating_sub(before.rx_bytes) as f64 / dt_s,
58                tx_bytes_per_s: now.tx_bytes.saturating_sub(before.tx_bytes) as f64 / dt_s,
59            })
60        })
61        .collect()
62}
63
64/// Read `/proc/net/dev`. Empty when it cannot be read.
65pub(super) fn read_net_dev() -> Vec<NetCounters> {
66    std::fs::read_to_string("/proc/net/dev")
67        .map(|t| parse_net_dev(&t))
68        .unwrap_or_default()
69}
70
71#[cfg(test)]
72mod tests {
73    use super::*;
74
75    const T0: &str = "\
76Inter-|   Receive                                                |  Transmit
77 face |bytes    packets errs drop fifo frame compressed multicast|bytes    packets errs drop fifo colls carrier compressed
78    lo: 5000 10 0 0 0 0 0 0 5000 10 0 0 0 0 0 0
79  eth0: 1000 10 0 0 0 0 0 0 4000 20 0 0 0 0 0 0
80  eth1:    0  0 0 0 0 0 0 0    0  0 0 0 0 0 0 0";
81
82    /// The header lines and the loopback are not interfaces to report.
83    #[test]
84    fn interfaces_are_read_without_the_loopback() {
85        assert_eq!(
86            parse_net_dev(T0),
87            vec![
88                NetCounters {
89                    iface: "eth0".into(),
90                    rx_bytes: 1000,
91                    tx_bytes: 4000
92                },
93                NetCounters {
94                    iface: "eth1".into(),
95                    rx_bytes: 0,
96                    tx_bytes: 0
97                },
98            ]
99        );
100    }
101
102    #[test]
103    fn rates_are_per_second_and_an_unused_interface_is_left_out() {
104        let prev = parse_net_dev(T0);
105        let cur = parse_net_dev(
106            &T0.replace("1000 10", "3000 10")
107                .replace("4000 20", "4500 20"),
108        );
109        assert_eq!(
110            net_rates(&prev, &cur, 2.0),
111            vec![NetRate {
112                iface: "eth0".into(),
113                rx_bytes_per_s: 1000.0,
114                tx_bytes_per_s: 250.0,
115            }]
116        );
117    }
118}