Skip to content

Commit d67ccb0

Browse files
authored
Merge pull request #26 from messense/windows-if-index
Windows `Interface.index` implementation
2 parents 5db50e8 + 8b55791 commit d67ccb0

File tree

2 files changed

+31
-10
lines changed

2 files changed

+31
-10
lines changed

src/lib.rs

Lines changed: 13 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ pub struct Interface {
2424
/// The address details of the interface.
2525
pub addr: IfAddr,
2626
/// The index of the interface.
27-
pub idx: Option<u32>,
27+
pub index: Option<u32>,
2828
}
2929

3030
impl Interface {
@@ -192,19 +192,19 @@ mod getifaddrs_posix {
192192
let name = unsafe { CStr::from_ptr(ifaddr.ifa_name) }
193193
.to_string_lossy()
194194
.into_owned();
195-
let idx = {
196-
let idx = unsafe { if_nametoindex(ifaddr.ifa_name) };
195+
let index = {
196+
let index = unsafe { if_nametoindex(ifaddr.ifa_name) };
197197

198198
// From `man if_nametoindex 3`:
199199
// The if_nametoindex() function maps the interface name specified in ifname to its
200200
// corresponding index. If the specified interface does not exist, it returns 0.
201-
if idx == 0 {
201+
if index == 0 {
202202
None
203203
} else {
204-
Some(idx)
204+
Some(index)
205205
}
206206
};
207-
ret.push(Interface { name, addr, idx });
207+
ret.push(Interface { name, addr, index });
208208
}
209209

210210
Ok(ret)
@@ -337,10 +337,14 @@ mod getifaddrs_windows {
337337
}
338338
};
339339

340+
let index = match addr {
341+
IfAddr::V4(_) => ifaddr.ipv4_index(),
342+
IfAddr::V6(_) => ifaddr.ipv6_index(),
343+
};
340344
ret.push(Interface {
341345
name: ifaddr.name(),
342346
addr,
343-
idx: None,
347+
index,
344348
});
345349
}
346350
}
@@ -454,7 +458,7 @@ mod tests {
454458
);
455459
// if index is set, it is non-zero
456460
for interface in &ifaces {
457-
if let Some(idx) = interface.idx {
461+
if let Some(idx) = interface.index {
458462
assert!(idx > 0);
459463
}
460464
}
@@ -475,8 +479,7 @@ mod tests {
475479
listed = true;
476480
}
477481

478-
#[cfg(not(windows))]
479-
assert!(interface.idx.is_some());
482+
assert!(interface.index.is_some());
480483
}
481484
assert!(listed);
482485
}

src/windows.rs

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,24 @@ impl IpAdapterAddresses {
2828
.into_owned()
2929
}
3030

31+
pub fn ipv4_index(&self) -> Option<u32> {
32+
let if_index = unsafe { (*self.0).Anonymous1.Anonymous.IfIndex };
33+
if if_index == 0 {
34+
None
35+
} else {
36+
Some(if_index)
37+
}
38+
}
39+
40+
pub fn ipv6_index(&self) -> Option<u32> {
41+
let if_index = unsafe { (*self.0).Ipv6IfIndex };
42+
if if_index == 0 {
43+
None
44+
} else {
45+
Some(if_index)
46+
}
47+
}
48+
3149
pub fn prefixes(&self) -> PrefixesIterator {
3250
PrefixesIterator {
3351
_head: unsafe { &*self.0 },

0 commit comments

Comments
 (0)