Skip to content

Commit

Permalink
Get rid of libc on Windows
Browse files Browse the repository at this point in the history
  • Loading branch information
messense committed Feb 28, 2023
1 parent c3b1ea8 commit 797a39e
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 7 deletions.
3 changes: 2 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,14 @@ repository = "https://github.com/messense/if-addrs"
version = "0.10.0"
edition = "2018"

[dependencies]
[target.'cfg(not(target_os = "windows"))'.dependencies]
libc = "0.2"

[target.'cfg(target_os = "windows")'.dependencies.windows-sys]
version = "0.45.0"
features = [
"Win32_Foundation",
"Win32_System_Memory",
"Win32_Networking_WinSock",
"Win32_NetworkManagement_IpHelper",
"Win32_NetworkManagement_Ndis",
Expand Down
15 changes: 9 additions & 6 deletions src/windows.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
// specific language governing permissions and limitations relating to use of the SAFE Network
// Software.

use libc::{self, c_ulong, c_void, size_t};
use std::ffi::CStr;
use std::{io, ptr};
use windows_sys::Win32::Foundation::{ERROR_BUFFER_OVERFLOW, ERROR_SUCCESS};
Expand All @@ -16,6 +15,9 @@ use windows_sys::Win32::NetworkManagement::IpHelper::{
GAA_FLAG_SKIP_FRIENDLY_NAME, 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,
};

#[repr(transparent)]
pub struct IpAdapterAddresses(*const IP_ADAPTER_ADDRESSES_LH);
Expand Down Expand Up @@ -68,12 +70,13 @@ pub struct IfAddrs {
impl IfAddrs {
#[allow(unsafe_code)]
pub fn new() -> io::Result<Self> {
let mut buffersize: c_ulong = 15000;
let mut buffersize = 15000;
let mut ifaddrs: *mut IP_ADAPTER_ADDRESSES_LH;

loop {
unsafe {
ifaddrs = libc::malloc(buffersize as size_t) as *mut IP_ADAPTER_ADDRESSES_LH;
ifaddrs = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, buffersize as _)
as *mut IP_ADAPTER_ADDRESSES_LH;
if ifaddrs.is_null() {
panic!("Failed to allocate buffer in get_if_addrs()");
}
Expand All @@ -93,12 +96,12 @@ impl IfAddrs {
match retcode {
ERROR_SUCCESS => break,
ERROR_BUFFER_OVERFLOW => {
libc::free(ifaddrs as *mut c_void);
HeapFree(GetProcessHeap(), HEAP_NONE, ifaddrs as _);
buffersize *= 2;
continue;
}
_ => {
libc::free(ifaddrs as *mut c_void);
HeapFree(GetProcessHeap(), HEAP_NONE, ifaddrs as _);
return Err(io::Error::last_os_error());
}
}
Expand All @@ -122,7 +125,7 @@ impl Drop for IfAddrs {
#[allow(unsafe_code)]
fn drop(&mut self) {
unsafe {
libc::free(self.inner.0 as *mut c_void);
HeapFree(GetProcessHeap(), HEAP_NONE, self.inner.0 as _);
}
}
}
Expand Down

0 comments on commit 797a39e

Please sign in to comment.