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!?");
                    }
                }
            }
        }
    }

      

+1


a source to share


4 answers


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.

0


a source


This is because you are faced with a feedback adapter. those. 127.0.0.1 They have IPv4Mask set to null. Refer to ni.Name to see if I am correct.

To check for a loopback adapter, run ...



if (ni.NetworkInterfaceType! = NetworkInterfaceType.Loopback) ...

+1


a source


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

+1


a source


One of the reasons I just ran into:

I am using .NET framework 4 Client profile, IPv4Mask worked great for me. When migrating to .NET framework 2 or 3.5, it returns NULL. I have reproduced this question repeatedly.

0


a source







All Articles