c++cwinapiiphelper

Get subnet mask from GetAdapterAddresses()


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()?


Solution

  • 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.