Skip to content

Commit

Permalink
Merge pull request #26 from messense/windows-if-index
Browse files Browse the repository at this point in the history
Windows `Interface.index` implementation
  • Loading branch information
messense committed Feb 28, 2023
2 parents 5db50e8 + 8b55791 commit d67ccb0
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 10 deletions.
23 changes: 13 additions & 10 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ pub struct Interface {
/// The address details of the interface.
pub addr: IfAddr,
/// The index of the interface.
pub idx: Option<u32>,
pub index: Option<u32>,
}

impl Interface {
Expand Down Expand Up @@ -192,19 +192,19 @@ mod getifaddrs_posix {
let name = unsafe { CStr::from_ptr(ifaddr.ifa_name) }
.to_string_lossy()
.into_owned();
let idx = {
let idx = unsafe { if_nametoindex(ifaddr.ifa_name) };
let index = {
let index = unsafe { if_nametoindex(ifaddr.ifa_name) };

// From `man if_nametoindex 3`:
// The if_nametoindex() function maps the interface name specified in ifname to its
// corresponding index. If the specified interface does not exist, it returns 0.
if idx == 0 {
if index == 0 {
None
} else {
Some(idx)
Some(index)
}
};
ret.push(Interface { name, addr, idx });
ret.push(Interface { name, addr, index });
}

Ok(ret)
Expand Down Expand Up @@ -337,10 +337,14 @@ mod getifaddrs_windows {
}
};

let index = match addr {
IfAddr::V4(_) => ifaddr.ipv4_index(),
IfAddr::V6(_) => ifaddr.ipv6_index(),
};
ret.push(Interface {
name: ifaddr.name(),
addr,
idx: None,
index,
});
}
}
Expand Down Expand Up @@ -454,7 +458,7 @@ mod tests {
);
// if index is set, it is non-zero
for interface in &ifaces {
if let Some(idx) = interface.idx {
if let Some(idx) = interface.index {
assert!(idx > 0);
}
}
Expand All @@ -475,8 +479,7 @@ mod tests {
listed = true;
}

#[cfg(not(windows))]
assert!(interface.idx.is_some());
assert!(interface.index.is_some());
}
assert!(listed);
}
Expand Down
18 changes: 18 additions & 0 deletions src/windows.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,24 @@ impl IpAdapterAddresses {
.into_owned()
}

pub fn ipv4_index(&self) -> Option<u32> {
let if_index = unsafe { (*self.0).Anonymous1.Anonymous.IfIndex };
if if_index == 0 {
None
} else {
Some(if_index)
}
}

pub fn ipv6_index(&self) -> Option<u32> {
let if_index = unsafe { (*self.0).Ipv6IfIndex };
if if_index == 0 {
None
} else {
Some(if_index)
}
}

pub fn prefixes(&self) -> PrefixesIterator {
PrefixesIterator {
_head: unsafe { &*self.0 },
Expand Down

0 comments on commit d67ccb0

Please sign in to comment.