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);
}
}
}
}
本文介绍了一种通过.NET框架获取计算机上每个IPv4地址的子网掩码的方法。利用System.Net.NetworkInformation命名空间中的类和属性,可以遍历所有网络接口并获取其IPv4配置信息。
454

被折叠的 条评论
为什么被折叠?



