#region 读取本地IP地址和子网页码
//读取本地IP地址和子网页码
NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface adapter in nics)
{
if (adapter.NetworkInterfaceType.ToString().Equals("Ethernet"))
{
//adapter.Name; //网卡适配名称:“本地连接”
//adapter.Description; //适配器描述信息
IPInterfaceProperties ip = adapter.GetIPProperties(); //IP配置信息 if (ip.UnicastAddresses.Count > )
{
string localip = ip.UnicastAddresses[].Address.ToString(); //IP地址
txtIP.Text = localip;
string localcode = ip.UnicastAddresses[].IPv4Mask.ToString(); //子网掩码
txtZWym.Text = localcode; }
if (ip.GatewayAddresses.Count > )
{
string net = ip.GatewayAddresses[].Address.ToString(); //默认网关
txtWg.Text = net;
} if (ip.DnsAddresses.Count > )
{
ip.DnsAddresses[].ToString(); //首选DNS服务器地址
if (ip.DnsAddresses.Count > )
ip.DnsAddresses[].ToString(); //备用DNS服务器地址
//MessageBox.Show(" ip.DnsAddresses[0].ToString();:" + ip.DnsAddresses[0].ToString());
}
}
}
#endregion
方法二:上面的方法有时候读不出来子网掩码,需要如下方法:
ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection nics = mc.GetInstances();
foreach (ManagementObject nic in nics)
{
if (Convert.ToBoolean(nic["ipEnabled"]) == true)
{
string mac = nic["MacAddress"].ToString();//Mac地址 string ip = (nic["IPAddress"] as String[])[];//IP地址
txtIP.Text = ip;
string ipsubnet = (nic["IPSubnet"] as String[])[];//子网掩码
txtZWym.Text = ipsubnet;
string ipgateway = (nic["DefaultIPGateway"] as String[])[];//默认网关
txtWg.Text = ipgateway;
}
}