Skip to main content

ferrix_lib/
net.rs

1/* net.rs
2 *
3 * Copyright 2026 Michail Krasnov <mskrasnov07@ya.ru>
4 *
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, either version 3 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
17 *
18 * SPDX-License-Identifier: GPL-3.0-or-later
19 */
20
21//! Network statistics
22
23use 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}