13

I'm using the GetAdapterAddresses() method to get the ip addresses of all interfaces on the system.

I need to find the broadcast address of each interface. I can calculate this using the IP address and the subnet mask but I can't see the subnet mask in the IP_ADAPTER_ADDRESSES structure.

Is there any way to retrieve the subnet mask using GetAdapterAddresses()?

jossgray
  • 497
  • 6
  • 20

1 Answers1

22

GetAdapterAddresses() provides subnet masks only on Vista and later.

When looping through the unicast addresses pointed to by the FirstUnicastAddress field of the IP_ADAPTER_ADDRESSES record, the IP_ADAPTER_UNICAST_ADDRESS record includes an OnLinkPrefixLength field. This field is not available on pre-Vista systems. This field is the length of the subnet mask, in bits. For IPv4 unicast addresses, you can use ConvertLengthToIpv4Mask() to convert the OnLinkPrefixLength value into a subnet mask, which you can then use to mask the unicast IPv4 address as needed.

On pre-Vista systems, use GetIpAddrTable() to get a list of the available IPv4 interfaces. The MIB_IPADDRROW record contains a dwAddr field for the IPv4 address, a dwMask field for the subnet mask, and a dwBCastAddr field for the broadcast address. You can loop through that table looking for each unicast IPv4 address reported by GetAdapterAddresses(), and then you will have their associated subnet masks and broadcast IP addresses.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • Is there a way to convert the ULONG returned by `ConvertLengthToIpv4Mask()` to a string representation (Like "255.255.255.0")? – jossgray Jul 13 '14 at 14:51
  • Ok I can use an in_addr structure and inet_ntoa. Thanks. – jossgray Jul 13 '14 at 14:55
  • 1
    Thanks for the great answer btw! Just want to add that the MSDN documentation for IP_ADAPTER_UNICAST_ADDRESS is wrong for Windows Embedded Compact 7. https://msdn.microsoft.com/en-us/library/ee494101(v=winembedded.70).aspx It doesn't list OnLinkPrefixLength, but looking at the .h files, it is there. I have confirmed that it is there. (Same for newer versions). It does not exist in CE 6 or lower (properly documented). – Bryan Jan 30 '15 at 19:49