次の方法で共有


Getting SubnetMask through System.Net.NetworkInformation

Some people have asked me how to get the SubnetMask for the network interfafce.
The subnet mask is valid only for IPv4.
The solution may not jump at you since there is no property called SubnetMask,
however there is a property called IPv4Mask.
Here is the code to get the subnet mask for each IPv4 address on the box

using System;
using System.Net.NetworkInformation;

public class test
{
public static void Main()
{
NetworkInterface[] Interfaces = NetworkInterface.GetAllNetworkInterfaces();
foreach(NetworkInterface Interface in Interfaces)
{
if(Interface.NetworkInterfaceType == NetworkInterfaceType.Loopback) continue;
Console.WriteLine(Interface.Description);
UnicastIPAddressInformationCollection UnicastIPInfoCol = Interface.GetIPProperties().UnicastAddresses;
foreach(UnicastIPAddressInformation UnicatIPInfo in UnicastIPInfoCol)
{
Console.WriteLine("\tIP Address is {0}", UnicatIPInfo.Address);
Console.WriteLine("\tSubnet Mask is {0}", UnicatIPInfo.IPv4Mask);
}
}
}
}

Comments