Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use user-visible adapter name on Windows #34

Merged
merged 1 commit into from
Apr 2, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,12 @@ pub struct Interface {
pub addr: IfAddr,
/// The index of the interface.
pub index: Option<u32>,
/// (Windows only) A permanent and unique identifier for the interface. It
/// cannot be modified by the user. It is typically a GUID string of the
/// form: "{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}", but this is not
/// guaranteed by the Windows API.
#[cfg(windows)]
pub adapter_name: String,
}

impl Interface {
Expand Down Expand Up @@ -345,6 +351,7 @@ mod getifaddrs_windows {
name: ifaddr.name(),
addr,
index,
adapter_name: ifaddr.adapter_name(),
});
}
}
Expand Down
16 changes: 12 additions & 4 deletions src/windows.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@ use std::{io, ptr};
use windows_sys::Win32::Foundation::{ERROR_BUFFER_OVERFLOW, ERROR_SUCCESS};
use windows_sys::Win32::NetworkManagement::IpHelper::{
GetAdaptersAddresses, GAA_FLAG_INCLUDE_PREFIX, GAA_FLAG_SKIP_ANYCAST, GAA_FLAG_SKIP_DNS_SERVER,
GAA_FLAG_SKIP_FRIENDLY_NAME, GAA_FLAG_SKIP_MULTICAST, IP_ADAPTER_ADDRESSES_LH,
IP_ADAPTER_PREFIX_XP, IP_ADAPTER_UNICAST_ADDRESS_LH,
GAA_FLAG_SKIP_MULTICAST, IP_ADAPTER_ADDRESSES_LH, IP_ADAPTER_PREFIX_XP,
IP_ADAPTER_UNICAST_ADDRESS_LH,
};
use windows_sys::Win32::System::Memory::{
GetProcessHeap, HeapAlloc, HeapFree, HEAP_NONE, HEAP_ZERO_MEMORY,
Expand All @@ -25,6 +25,15 @@ pub struct IpAdapterAddresses(*const IP_ADAPTER_ADDRESSES_LH);
impl IpAdapterAddresses {
#[allow(unsafe_code)]
pub fn name(&self) -> String {
let len = (0..)
.take_while(|&i| unsafe { *(*self.0).FriendlyName.offset(i) } != 0)
.count();
let slice = unsafe { std::slice::from_raw_parts((*self.0).FriendlyName, len) };
String::from_utf16_lossy(slice)
}

#[allow(unsafe_code)]
pub fn adapter_name(&self) -> String {
unsafe { CStr::from_ptr((*self.0).AdapterName as _) }
.to_string_lossy()
.into_owned()
Expand Down Expand Up @@ -86,8 +95,7 @@ impl IfAddrs {
GAA_FLAG_SKIP_ANYCAST
| GAA_FLAG_SKIP_MULTICAST
| GAA_FLAG_SKIP_DNS_SERVER
| GAA_FLAG_INCLUDE_PREFIX
| GAA_FLAG_SKIP_FRIENDLY_NAME,
| GAA_FLAG_INCLUDE_PREFIX,
ptr::null_mut(),
ifaddrs,
&mut buffersize,
Expand Down
Loading