]>
code.octet-stream.net Git - netwatcher/blob - src/list_unix.rs
a6b2bd3bec616d4237f86801e92b96c13cbcee47
2 use std
::{collections
::HashMap
, net
::IpAddr
};
6 use nix
::{ifaddrs
::getifaddrs
, net
::if_
::if_nametoindex
};
8 use crate::{Error
, IfIndex
, Interface
};
10 struct CandidateInterface
{
13 hw_addr
: Option
<String
>,
17 pub(crate) fn list_interfaces() -> Result
<HashMap
<IfIndex
, Interface
>, Error
> {
18 let addrs
= getifaddrs().map_err(|_
| Error
::Internal
)?
;
19 let mut candidates
= HashMap
::new();
22 let index
= if_nametoindex(addr
.inter
face
_name
.as_str()).map_err(|_
| Error
::Internal
)?
;
23 let candidate
= candidates
24 .entry(addr
.inter
face
_name
.clone())
25 .or_insert_with(|| CandidateInterface
{
26 name
: addr
.inter
face
_name
.clone(),
31 if let Some(a
) = addr
.address
{
32 if let Some(a
) = a
.as_link_addr() {
33 if let Some(raw_addr
) = a
.addr() {
34 candidate
.hw_addr
= Some(format_mac(&raw_addr
)?
);
37 if let Some(a
) = a
.as_sockaddr_in() {
38 candidate
.ips
.push(IpAddr
::V4(a
.ip
()));
40 if let Some(a
) = a
.as_sockaddr_in6() {
41 candidate
.ips
.push(IpAddr
::V6(a
.ip
()));
49 c
.hw_addr
.map(|hw_addr
| {
65 fn format_mac(bytes
: &[u8]) -> Result
<String
, Error
> {
66 let mut mac
= String
::with_capacity(bytes
.len() * 3);
67 for i
in 0..bytes
.len() {
69 write
!(mac
, ":").map_err(|_
| Error
::Internal
)?
;
71 write
!(mac
, "{:02X}", bytes
[i
]).map_err(|_
| Error
::Internal
)?
;