use std::ffi::CString;
#[derive(Debug, Clone)]
pub struct Device {
pub name: String,
pub ifindex: Option<u32>,
}
impl Device {
pub fn lookup(name: &str) -> std::io::Result<Self> {
let cname = CString::new(name)
.map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidInput, e))?;
let idx = unsafe { libc::if_nametoindex(cname.as_ptr()) };
if idx == 0 {
Err(std::io::Error::last_os_error())
} else {
Ok(Self {
name: name.to_owned(),
ifindex: Some(idx),
})
}
}
pub fn any() -> Self {
Self {
name: "any".to_owned(),
ifindex: None,
}
}
}
impl std::fmt::Display for Device {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.name)
}
}