Skip to content

Commit

Permalink
Merge pull request #34 from mon/windows-friendly-name
Browse files Browse the repository at this point in the history
Use user-visible adapter name on Windows
  • Loading branch information
messense authored Apr 2, 2024
2 parents adcf2b5 + 89aca06 commit 93fee9d
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 4 deletions.
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

0 comments on commit 93fee9d

Please sign in to comment.