从WMI获取网络接口IP信息(摘抄)
本文摘抄自《C#网络应用编程》 电子工业出版社 [美]Richard Blum著 根据需要做了些小小变动。 PS:WMI的详信息可以看MSDN |
using System.Management;
class WMICardGrab
{
public static void Main()
{
string _getIPcmd = " SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = 'TRUE' " ;
ManagementObjectSearcher query = new ManagementObjectSearcher(_getIPcmd);
ManagementObjectCollection queryCollection = query.Get();
foreach (ManagementObject mo in queryCollection)
{
string [] addresses = ( string [])mo[ " IPAddress " ];
string [] subnets = ( string [])mo[ " IPSubnet " ];
string [] defaultgateways = ( string [])mo[ " DefaultIPGateway " ];
Console.WriteLine( " 网卡: {0} " , mo[ " Description " ]);
Console.WriteLine( " \tMAC地址: {0} " , mo[ " MACAddress " ]);
foreach ( string ipaddress in addresses)
{
Console.WriteLine( " \tIP地址: {0} " , ipaddress);
}
foreach ( string subnet in subnets)
{
Console.WriteLine( " \t子网掩码: {0} " , subnet);
}
foreach ( string defaultgateway in defaultgateways)
{
Console.WriteLine( " \t默认网关: {0} " , defaultgateway);
}
}
Console.ReadLine();
}
}
class WMICardGrab
{
public static void Main()
{
string _getIPcmd = " SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = 'TRUE' " ;
ManagementObjectSearcher query = new ManagementObjectSearcher(_getIPcmd);
ManagementObjectCollection queryCollection = query.Get();
foreach (ManagementObject mo in queryCollection)
{
string [] addresses = ( string [])mo[ " IPAddress " ];
string [] subnets = ( string [])mo[ " IPSubnet " ];
string [] defaultgateways = ( string [])mo[ " DefaultIPGateway " ];
Console.WriteLine( " 网卡: {0} " , mo[ " Description " ]);
Console.WriteLine( " \tMAC地址: {0} " , mo[ " MACAddress " ]);
foreach ( string ipaddress in addresses)
{
Console.WriteLine( " \tIP地址: {0} " , ipaddress);
}
foreach ( string subnet in subnets)
{
Console.WriteLine( " \t子网掩码: {0} " , subnet);
}
foreach ( string defaultgateway in defaultgateways)
{
Console.WriteLine( " \t默认网关: {0} " , defaultgateway);
}
}
Console.ReadLine();
}
}