X-Git-Url: https://code.octet-stream.net/netwatcher/blobdiff_plain/9ea683eddb05362f02bca60e4337955dfc5871dc..8f78cf14e9d177b9dfd43b6b35038d391821627e:/src/list_unix.rs diff --git a/src/list_unix.rs b/src/list_unix.rs index 4ae0fc7..4a49140 100644 --- a/src/list_unix.rs +++ b/src/list_unix.rs @@ -1,11 +1,9 @@ +use std::fmt::Write; use std::{collections::HashMap, net::IpAddr}; -use block2::Block; -use nix::libc::c_long; use nix::{ifaddrs::getifaddrs, net::if_::if_nametoindex}; -use crate::util::format_mac; -use crate::{Error, IfIndex, Interface}; +use crate::{Error, Interface, List}; struct CandidateInterface { name: String, @@ -14,12 +12,13 @@ struct CandidateInterface { ips: Vec, } -pub(crate) fn list_interfaces() -> Result, Error> { - let addrs = getifaddrs().map_err(|_| Error::Internal)?; +pub(crate) fn list_interfaces() -> Result { + let addrs = getifaddrs().map_err(|e| Error::Getifaddrs(e.to_string()))?; let mut candidates = HashMap::new(); for addr in addrs { - let index = if_nametoindex(addr.interface_name.as_str()).map_err(|_| Error::Internal)?; + let index = if_nametoindex(addr.interface_name.as_str()) + .map_err(|e| Error::GetInterfaceName(e.to_string()))?; let candidate = candidates .entry(addr.interface_name.clone()) .or_insert_with(|| CandidateInterface { @@ -59,41 +58,16 @@ pub(crate) fn list_interfaces() -> Result, Error> { }) }) .collect(); - Ok(ifs) + Ok(List(ifs)) } -// The "objc2" project aims to provide bindings for all frameworks but Network.framework -// isn't ready yet so let's kick it old-school - -struct nw_path_monitor; -type nw_path_monitor_t = *mut nw_path_monitor; -struct nw_path; -type nw_path_t = *mut nw_path; -struct dispatch_queue; -type dispatch_queue_t = *mut dispatch_queue; -const QOS_CLASS_BACKGROUND: usize = 0x09; - -#[link(name = "Network", kind = "framework")] -extern "C" { - fn nw_path_monitor_create() -> nw_path_monitor_t; - fn nw_path_monitor_set_update_handler( - monitor: nw_path_monitor_t, - update_handler: &Block, - ); - fn nw_path_monitor_set_queue(monitor: nw_path_monitor_t, queue: dispatch_queue_t); - fn nw_path_monitor_start(monitor: nw_path_monitor_t); - fn nw_path_monitor_cancel(monitor: nw_path_monitor_t); - - fn dispatch_get_global_queue(identifier: usize, flag: usize) -> dispatch_queue_t; -} - -#[cfg(test)] -mod test { - use super::list_interfaces; - - #[test] - fn list() { - let ifaces = list_interfaces().unwrap(); - println!("{:?}", ifaces); +fn format_mac(bytes: &[u8]) -> Result { + let mut mac = String::with_capacity(bytes.len() * 3); + for (i, b) in bytes.iter().enumerate() { + if i != 0 { + write!(mac, ":").map_err(|_| Error::FormatMacAddress)?; + } + write!(mac, "{:02X}", b).map_err(|_| Error::FormatMacAddress)?; } + Ok(mac) }