user2928068
user2928068

Reputation: 41

C# can't get the correct subnetmask

I am making a program that among other things collects system information. However I am having some problems obtaining the subnet mask. I am new to programming so this is probably related to my lack of skills. My code looks like this:

public string Subnet()
{
     string Maske = "";
     foreach (NetworkInterface f in NetworkInterface.GetAllNetworkInterfaces())
     if (f.OperationalStatus == OperationalStatus.Up)
     {
         IPInterfaceProperties ipInterface = f.GetIPProperties();
         foreach (UnicastIPAddressInformation unicastAddress in ipInterface.UnicastAddresses)
         {
             Maske = unicastAddress.IPv4Mask.ToString();
         }
     }
     return Maske;
}

I only get 255.0.0.0 as a result. I have disabled or uninstalled the other network cards but I still get this result.

Upvotes: 0

Views: 369

Answers (1)

Udontknow
Udontknow

Reputation: 1578

Are you aware that there may be more than one entry in in ipInterface.UnicastAddresses or NetworkInterface.GetAllNetworkInterfaces()? Your method only takes the last one found. I tested your method on my pc, and the list contained three entries: 255.255.255.0, 0.0.0.0 and 255.0.0.0...

EDIT: You may need to ignore network interfaces with the NetworkInterfaceType Loopback, as there are sometimes some virtual software interfaces installed...

if (f.OperationalStatus == OperationalStatus.Up && f.NetworkInterfaceType != NetworkInterfaceType.Loopback)

Upvotes: 1

Related Questions