use core::{fmt, time::Duration};
use std::{net::IpAddr, time::Instant};
use crate::{Bytes, Error, Rate, Result};
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct Interface {
pub name: String,
pub index: u32,
pub description: Option<String>,
pub kind: InterfaceKind,
pub mac: Option<Mac>,
pub addresses: Vec<IpNet>,
pub up: bool,
pub running: bool,
pub mtu: Option<u32>,
pub speed_mbps: Option<u64>,
pub is_physical: bool,
}
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
#[non_exhaustive]
pub enum InterfaceKind {
Ethernet,
Wifi,
Loopback,
Tunnel,
Bridge,
Virtual,
Cellular,
Other,
}
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
#[non_exhaustive]
pub struct Mac {
pub bytes: [u8; 6],
pub kind: MacKind,
}
impl Mac {
#[allow(dead_code)] pub(crate) fn from_bytes(bytes: [u8; 6]) -> Mac {
let kind = if bytes[0] & 0x02 != 0 {
MacKind::Random
} else {
MacKind::Permanent
};
Mac { bytes, kind }
}
}
impl fmt::Display for Mac {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let b = self.bytes;
write!(
f,
"{:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}",
b[0], b[1], b[2], b[3], b[4], b[5]
)
}
}
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
#[non_exhaustive]
pub enum MacKind {
Permanent,
Random,
Unknown,
}
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
pub struct IpNet {
pub addr: IpAddr,
pub prefix: u8,
}
impl fmt::Display for IpNet {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}/{}", self.addr, self.prefix)
}
}
#[derive(Clone, Copy, Debug)]
#[non_exhaustive]
pub struct InterfaceOptions {
pub include_down: bool,
pub include_loopback: bool,
pub details: bool,
pub max_interfaces: usize,
}
impl Default for InterfaceOptions {
fn default() -> Self {
InterfaceOptions {
include_down: true,
include_loopback: true,
details: true,
max_interfaces: 4_096,
}
}
}
pub fn interfaces() -> Result<Vec<Interface>> {
interfaces_with(InterfaceOptions::default())
}
pub fn interfaces_with(options: InterfaceOptions) -> Result<Vec<Interface>> {
let mut list = crate::sys::interfaces(&options)?;
list.retain(|i| {
(options.include_down || i.up)
&& (options.include_loopback || i.kind != InterfaceKind::Loopback)
});
list.sort_by(|a, b| a.index.cmp(&b.index).then_with(|| a.name.cmp(&b.name)));
Ok(list)
}
pub fn primary() -> Result<Option<Interface>> {
let Some(index) = crate::sys::primary_interface()? else {
return Ok(None);
};
Ok(interfaces()?.into_iter().find(|i| i.index == index))
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct Dns {
pub servers: Vec<IpAddr>,
pub upstream: Vec<IpAddr>,
pub search: Vec<String>,
}
pub fn dns() -> Result<Dns> {
crate::sys::dns()
}
pub fn addresses() -> Result<Vec<IpAddr>> {
let options = InterfaceOptions {
include_down: false,
include_loopback: false,
details: false,
..InterfaceOptions::default()
};
let mut out: Vec<IpAddr> = interfaces_with(options)?
.into_iter()
.flat_map(|i| i.addresses)
.map(|n| n.addr)
.filter(|a| !a.is_loopback() && !is_link_local(a))
.collect();
out.dedup();
Ok(out)
}
fn is_link_local(addr: &IpAddr) -> bool {
match addr {
IpAddr::V4(v4) => v4.is_link_local(),
IpAddr::V6(v6) => (v6.segments()[0] & 0xffc0) == 0xfe80,
}
}
#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
#[non_exhaustive]
pub struct Totals {
pub received: Bytes,
pub sent: Bytes,
pub packets_received: u64,
pub packets_sent: u64,
pub errors: u64,
pub dropped: u64,
}
#[derive(Clone, Copy, PartialEq, Debug)]
#[non_exhaustive]
pub struct Traffic {
pub download: Rate,
pub upload: Rate,
pub packets_in_per_sec: f64,
pub packets_out_per_sec: f64,
pub interval: Duration,
}
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub struct InterfaceTraffic {
pub interface: String,
pub traffic: Traffic,
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct Counters {
pub interface: String,
pub received: Bytes,
pub sent: Bytes,
pub packets_received: u64,
pub packets_sent: u64,
pub errors_in: u64,
pub errors_out: u64,
pub dropped_in: u64,
pub dropped_out: u64,
}
impl Totals {
#[allow(dead_code)] pub(crate) fn add(&mut self, c: &Counters) {
self.received = self.received.saturating_add(c.received);
self.sent = self.sent.saturating_add(c.sent);
self.packets_received = self.packets_received.saturating_add(c.packets_received);
self.packets_sent = self.packets_sent.saturating_add(c.packets_sent);
self.errors = self
.errors
.saturating_add(c.errors_in)
.saturating_add(c.errors_out);
self.dropped = self
.dropped
.saturating_add(c.dropped_in)
.saturating_add(c.dropped_out);
}
fn since(&self, earlier: &Totals, interval: Duration) -> Traffic {
let d = |new: u64, old: u64| new.saturating_sub(old);
let secs = interval.as_secs_f64();
let per_sec = |n: u64| if secs > 0.0 { n as f64 / secs } else { 0.0 };
Traffic {
download: Rate::from_delta(d(self.received.raw(), earlier.received.raw()), interval),
upload: Rate::from_delta(d(self.sent.raw(), earlier.sent.raw()), interval),
packets_in_per_sec: per_sec(d(self.packets_received, earlier.packets_received)),
packets_out_per_sec: per_sec(d(self.packets_sent, earlier.packets_sent)),
interval,
}
}
}
impl Counters {
fn as_totals(&self) -> Totals {
let mut t = Totals::default();
t.add(self);
t
}
}
pub const DEFAULT_WINDOW: Duration = Duration::from_secs(1);
const MIN_WINDOW: Duration = Duration::from_millis(100);
const MAX_WINDOW: Duration = Duration::from_secs(60);
pub fn totals() -> Result<Totals> {
crate::sys::net_totals()
}
pub fn counters() -> Result<Vec<Counters>> {
crate::sys::net_counters()
}
pub fn traffic() -> Result<Traffic> {
traffic_over(DEFAULT_WINDOW)
}
pub fn traffic_over(window: Duration) -> Result<Traffic> {
let mut sampler = Sampler::totals_only()?;
std::thread::sleep(window.clamp(MIN_WINDOW, MAX_WINDOW));
sampler.sample()
}
#[derive(Debug)]
pub struct Sampler {
total: Totals,
at: Instant,
interfaces: Vec<Counters>,
interfaces_at: Instant,
}
impl Sampler {
pub fn new() -> Result<Sampler> {
let now = Instant::now();
Ok(Sampler {
total: totals()?,
at: now,
interfaces: counters()?,
interfaces_at: now,
})
}
fn totals_only() -> Result<Sampler> {
let now = Instant::now();
Ok(Sampler {
total: totals()?,
at: now,
interfaces: Vec::new(),
interfaces_at: now,
})
}
pub fn sample(&mut self) -> Result<Traffic> {
let now = totals()?;
let at = Instant::now();
let interval = at.duration_since(self.at);
if interval.is_zero() {
return Err(too_soon(interval));
}
let traffic = now.since(&self.total, interval);
self.total = now;
self.at = at;
Ok(traffic)
}
pub fn sample_per_interface(&mut self) -> Result<Vec<InterfaceTraffic>> {
let now = counters()?;
let at = Instant::now();
let interval = at.duration_since(self.interfaces_at);
if interval.is_zero() {
return Err(too_soon(interval));
}
let out = now
.iter()
.map(|c| {
let current = c.as_totals();
let earlier = self
.interfaces
.iter()
.find(|e| e.interface == c.interface)
.map_or(current, Counters::as_totals);
InterfaceTraffic {
interface: c.interface.clone(),
traffic: current.since(&earlier, interval),
}
})
.collect();
self.interfaces = now;
self.interfaces_at = at;
Ok(out)
}
}
fn too_soon(elapsed: Duration) -> Error {
Error::TooSoon {
elapsed,
minimum: Duration::from_millis(1),
}
}
#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
#[non_exhaustive]
pub struct Connections {
pub tcp_established: Option<u64>,
pub tcp_time_wait: Option<u64>,
pub tcp_total: Option<u64>,
pub udp: Option<u64>,
}
pub fn connections() -> Result<Connections> {
crate::sys::connections()
}
#[cfg(test)]
mod tests {
use std::net::{Ipv4Addr, Ipv6Addr};
use super::*;
#[test]
fn test_net_mac_display_and_kind() {
let m = Mac::from_bytes([0x00, 0x1b, 0x21, 0xaa, 0xbb, 0x0c]);
assert_eq!(m.to_string(), "00:1b:21:aa:bb:0c");
assert_eq!(m.kind, MacKind::Permanent);
assert_eq!(Mac::from_bytes([0x02, 0, 0, 0, 0, 1]).kind, MacKind::Random);
let n = IpNet {
addr: IpAddr::V4(Ipv4Addr::new(192, 168, 1, 20)),
prefix: 24,
};
assert_eq!(n.to_string(), "192.168.1.20/24");
assert!(is_link_local(&IpAddr::V6(Ipv6Addr::new(
0xfe80, 0, 0, 0, 0, 0, 0, 1
))));
assert!(!is_link_local(&IpAddr::V6(Ipv6Addr::new(
0x2001, 0xdb8, 0, 0, 0, 0, 0, 1
))));
}
#[test]
fn test_net_traffic_and_backwards_counters() {
let c = |rx: u64, tx: u64, prx: u64| Counters {
interface: "eth0".to_owned(),
received: Bytes::new(rx),
sent: Bytes::new(tx),
packets_received: prx,
packets_sent: 0,
errors_in: 1,
errors_out: 2,
dropped_in: 3,
dropped_out: 4,
};
let a = c(1_000_000, 0, 100).as_totals();
let b = c(2_000_000, 500_000, 300).as_totals();
assert_eq!((b.errors, b.dropped), (3, 7));
let t = b.since(&a, Duration::from_secs(2));
assert_eq!(t.download.bytes_per_sec(), 500_000);
assert_eq!(t.upload.bytes_per_sec(), 250_000);
assert!((t.packets_in_per_sec - 100.0).abs() < 1e-9);
let back = a.since(&b, Duration::from_secs(1));
assert_eq!((back.download, back.upload), (Rate::ZERO, Rate::ZERO));
}
#[test]
fn test_net_live_readings() {
let list = interfaces().unwrap();
assert!(
list.windows(2)
.all(|w| (w[0].index, &w[0].name) <= (w[1].index, &w[1].name))
);
for i in &list {
assert!(!i.name.is_empty());
}
let up = interfaces_with(InterfaceOptions {
include_down: false,
include_loopback: false,
details: false,
..InterfaceOptions::default()
})
.unwrap();
assert!(up.iter().all(|i| i.up && i.kind != InterfaceKind::Loopback));
for a in addresses().unwrap() {
assert!(!a.is_loopback() && !is_link_local(&a));
}
let t = totals().unwrap();
let _ = (t.received, t.sent);
let _ = connections().unwrap();
}
}