Skip to content

Commit 291472d

Browse files
committed
more comments on intricacies of windows api
1 parent e185ea7 commit 291472d

File tree

1 file changed

+7
-3
lines changed

1 file changed

+7
-3
lines changed

src/wgapi_windows.rs

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -81,9 +81,12 @@ fn guid_from_str(s: &str) -> Result<windows::core::GUID, WindowsError> {
8181
/// Example adapter name: "Ethernet", "WireGuard".
8282
fn get_adapter_guid(adapter_name: &str) -> Result<GUID, WindowsError> {
8383
debug!("Finding adapter {adapter_name}");
84-
// Get `buffer_size` to hold the adapters
84+
// We have to call `GetAdaptersAddresses` twice - first call to just get the `buffer_size` to hold the adapters.
85+
// Before the second call we allocate the buffer with `buffer_size` capacity so that the call can actually
86+
// store the adapters in the buffer.
8587
let mut buffer_size: u32 = 0;
8688
let mut result = unsafe {
89+
// Sets the `buffer_size`
8790
GetAdaptersAddresses(
8891
AF_UNSPEC.0 as u32,
8992
GAA_FLAG_INCLUDE_PREFIX,
@@ -92,11 +95,13 @@ fn get_adapter_guid(adapter_name: &str) -> Result<GUID, WindowsError> {
9295
&mut buffer_size,
9396
)
9497
};
98+
99+
// We expect the overflow here, since `buffer_size = 0`. No overflow means no adapters.
95100
if result != ERROR_BUFFER_OVERFLOW.0 {
96101
return Err(WindowsError::EmptyInterfaceArrayError);
97102
}
98103

99-
// Actually get the adapters
104+
// Allocate the buffer and actually get the adapters
100105
let mut buffer: Vec<u8> = vec![0; buffer_size as usize];
101106
let addresses = buffer.as_mut_ptr() as *mut IP_ADAPTER_ADDRESSES_LH;
102107
result = unsafe {
@@ -125,7 +130,6 @@ fn get_adapter_guid(adapter_name: &str) -> Result<GUID, WindowsError> {
125130
let adapter = unsafe { &*current };
126131

127132
let friendly_name = unsafe { PCWSTR(adapter.FriendlyName.0).to_string()? };
128-
129133
if friendly_name == adapter_name {
130134
let adapter_name_str = unsafe { PCSTR(PSTR(adapter.AdapterName.0).0).to_string()? };
131135
guid = Some(guid_from_str(&adapter_name_str)?);

0 commit comments

Comments
 (0)