1use anyhow::Result;
24use serde::{Deserialize, Serialize};
25use std::{
26 fs::{read_dir, read_to_string},
27 path::PathBuf,
28};
29
30use crate::traits::ToJson;
31
32const NET_DIR: &str = "/sys/class/net/";
33
34#[derive(Debug, Clone, Deserialize, Serialize)]
35pub struct Networks {
36 pub networks: Vec<Network>,
37}
38
39impl Networks {
40 pub fn new() -> Result<Self> {
41 let net_dirs = read_dir(NET_DIR)?;
42 let mut networks = Vec::new();
43 for dir in net_dirs {
44 let dir = dir?.path();
45 networks.push(Network::new(&dir)?);
46 }
47 Ok(Self { networks })
48 }
49}
50
51impl ToJson for Networks {}
52
53#[derive(Debug, Clone, Deserialize, Serialize)]
54pub struct Network {
55 pub name: String,
56 pub address: String,
57 pub broadcast: String,
58 pub mtu: u64,
59 pub operstate: String,
60}
61
62impl Network {
63 pub fn new(path: &PathBuf) -> Result<Self> {
64 let name = path.strip_prefix(NET_DIR)?.display().to_string();
65 let address = read_to_string(path.join("address"))
66 .and_then(|address| Ok(address.trim().to_string()))?;
67 let broadcast = read_to_string(path.join("broadcast"))
68 .and_then(|broadcast| Ok(broadcast.trim().to_string()))?;
69 let mtu = read_to_string(path.join("mtu"))
70 .and_then(|mtu| Ok(mtu.trim().parse::<u64>().unwrap_or(0)))?;
71 let operstate = read_to_string(path.join("operstate"))
72 .and_then(|opstate| Ok(opstate.trim().to_string()))?;
73
74 Ok(Self {
75 name,
76 address,
77 broadcast,
78 mtu,
79 operstate,
80 })
81 }
82}