How to allocate memory for an FFI call

Just watch out when using this solution: you'll have to be careful to handle the ERROR_NO_DATA case and not attempt to allocate a buffer if you get it from the first GetAdaptersAddresses() call, since std::alloc::alloc() does not accept a 0-size layout. Also, you'll have to check if alloc() returns ptr::null(), and not attempt to use the pointer. Way too many crates have been bitten by not properly checking these things.

Meanwhile, the documentation for GetAdaptersAddresses() discourages this particular method:

One method that can be used to determine the memory needed to return the IP_ADAPTER_ADDRESSES structures pointed to by the AdapterAddresses parameter is to pass too small a buffer size as indicated in the SizePointer parameter in the first call to the GetAdaptersAddresses function, so the function will fail with ERROR_BUFFER_OVERFLOW. When the return value is ERROR_BUFFER_OVERFLOW, the SizePointer parameter returned points to the required size of the buffer to hold the adapter information. Note that it is possible for the buffer size required for the IP_ADAPTER_ADDRESSES structures pointed to by the AdapterAddresses parameter to change between subsequent calls to the GetAdaptersAddresses function if an adapter address is added or removed. However, this method of using the GetAdaptersAddresses function is strongly discouraged. This method requires calling the GetAdaptersAddresses function multiple times.

Instead, it recommends starting with size 15000, and using a larger allocation if you get ERROR_BUFFER_OVERFLOW.

One problem might be that if you look at the fields of IP_ADAPTER_ADDRESSES_LH, it contains pointers to other types such as IP_ADAPTER_UNICAST_ADDRESS_LH, IP_ADAPTER_ANYCAST_ADDRESS_XP, IP_ADAPTER_MULTICAST_ADDRESS_XP, IP_ADAPTER_DNS_SERVER_ADDRESS_XP, IP_ADAPTER_PREFIX_XP, IP_ADAPTER_WINS_SERVER_ADDRESS_LH, IP_ADAPTER_GATEWAY_ADDRESS_LH, and IP_ADAPTER_DNS_SUFFIX. So even though the buffer starts with an IP_ADAPTER_ADDRESSES_LH, that may not be the only thing it contains.

1 Like