Question

The following is a section of code which builds a list of IP addresses and their subnet masks from the local system, however the Warn function seems to get triggered regularly which should in theory be impossible - as it should not be possible to have an IPv4 address without the associated 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!?");
                    }
                }
            }
        }
    }
Was it helpful?

Solution

That is rather odd; obviously the semantics of this are not quite what one could reasonably expect.

Can you check to see if the subnet masks of the interfaces in question are classful? I.e., for those interface addresses where IPv4Mask is null, are they class A, B and C addresses with a network mask of /8, /16 and /24 respectively?

Perhaps this function is not really a member of the CIDR world, and they really do only "subnet" masks; an address without one is assumed to use the classful network mask.

OTHER TIPS

It is because you have come across a loop back adapter. ie 127.0.0.1 These have the IPv4Mask set to null. Refer to ni.Name to see if I am right.

To check for a loopback adapter do...

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

IPv4Mask returns null when the network is down (see ni.OperationalStatus), which you'll often encounter when iterating through everything GetAllNetworkInterfaces() returns.

This appears to have been fixed in .Net 4.0

Sometimes the masks can be inferred, e.g. all IP addresses that start with 169.254 (which is what Windows will pick when DHCP fails) have a mask of 255.255.0.0

One reason I've just come across:

I use .NET framework 4 Client profile, IPv4Mask worked fine with me. When switching to .NET framework 2 or 3.5, It returned NULL. I reproduced the issue multiple times .

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top