#[cfg(feature = "mac")]
use mac_address::MacAddress;
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};
use std::fmt::{Debug, Display};
use std::net::{Ipv4Addr, Ipv6Addr};
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
pub struct NetworkInterface {
pub name: String,
pub index: u32,
#[cfg(feature = "ipv4")]
pub v4_addr: Vec<V4IfAddr>,
#[cfg(feature = "ipv6")]
pub v6_addr: Vec<V6IfAddr>,
#[cfg(feature = "mac")]
pub mac_addr: Option<MacAddress>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
pub struct V4IfAddr {
pub ip: Ipv4Addr,
pub broadcast: Option<Ipv4Addr>,
pub netmask: Option<Ipv4Addr>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
pub struct V6IfAddr {
pub ip: Ipv6Addr,
pub broadcast: Option<Ipv6Addr>,
pub netmask: Option<Ipv6Addr>,
}
impl NetworkInterface {
pub fn new(name: String, index: u32) -> Self {
NetworkInterface {
name,
index,
#[cfg(feature = "ipv4")]
v4_addr: Vec::new(),
#[cfg(feature = "ipv6")]
v6_addr: Vec::new(),
#[cfg(feature = "mac")]
mac_addr: None,
}
}
#[cfg(feature = "ipv4")]
pub fn add_v4(&mut self, ip: Ipv4Addr, broadcast: Option<Ipv4Addr>, netmask: Option<Ipv4Addr>) {
let v4 = V4IfAddr {
ip,
broadcast,
netmask,
};
self.v4_addr.push(v4);
}
#[cfg(feature = "ipv6")]
pub fn add_v6(&mut self, ip: Ipv6Addr, broadcast: Option<Ipv6Addr>, netmask: Option<Ipv6Addr>) {
let v6 = V6IfAddr {
ip,
broadcast,
netmask,
};
self.v6_addr.push(v6);
}
}
impl Display for NetworkInterface {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
writeln!(f, "{}. {}", self.index, self.name)?;
if let Some(mac) = self.mac_addr {
write!(f, " link: {mac}\n")?;
};
for v4_addr in self.v4_addr.iter() {
write!(f, "{}", v4_addr)?
}
for v6_addr in self.v6_addr.iter() {
write!(f, "{}", v6_addr)?
}
Ok(())
}
}
impl Display for V4IfAddr {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, " ipv4: {}\n", self.ip)?;
if let Some(netmask) = self.netmask {
write!(f, " netmask: {netmask}\n")?;
};
if let Some(broadcast) = self.broadcast {
write!(f, " broadcast: {broadcast}\n")?;
};
Ok(())
}
}
impl Display for V6IfAddr {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, " ipv6: {}\n", self.ip)?;
if let Some(netmask) = self.netmask {
write!(f, " netmask: {netmask}\n")?;
};
if let Some(broadcast) = self.broadcast {
write!(f, " broadcast: {broadcast}\n")?;
};
Ok(())
}
}