Why does UnicastIPAddressInformation.IPv4Mask return null to IPv4 address?
Below is a code snippet that builds a list of IP addresses and their subnet masks from the local system, however the Warn function seems to fire regularly, which is theoretically impossible, since there shouldn't be an IPv4 address without a matching subnet mask [?].
static NetworkUtil()
{
foreach (NetworkInterface ni in NetworkInterface.GetAllNetworkInterfaces())
{
foreach (UnicastIPAddressInformation address in ni.GetIPProperties().UnicastAddresses)
{
if (address.Address.AddressFamily == AddressFamily.InterNetwork)
{
if (address.IPv4Mask != null)
{
m_subnets.Add(address.Address, address.IPv4Mask);
}
else
{
m_log.Warn("[NetworkUtil] Found IPv4 Address without Subnet Mask!?");
}
}
}
}
}
a source to share
It's pretty weird; obviously the semantics of this are not quite what one would reasonably expect.
Can you check if the subnet masks of the interfaces in question are cool? Ie, for those interface addresses where IPv4Mask
is null, are they class A, B, and C with netmask / 8, / 16 and / 24 respectively?
Perhaps this feature is not really a member of the CIDR world, and they really only do subnet masks; an address without it is supposed to use a cool netmask.
a source to share
IPv4Mask returns null when the network is down (see ni.OperationalStatus), which you often encounter when repeating all the results of GetAllNetworkInterfaces ().
This appears to have been fixed in .Net 4.0
Sometimes masks can be inferred, for example. all IP addresses starting with 169.254 (which is what Windows will choose if DHCP fails) have a mask of 255.255.0.0
a source to share