在我的C#程序中,我需要枚举所有实际网络接口(Wifi或以太网),也就是连接到实际物理设备的接口,而不是VPN连接等等。
我正在使用
我正在使用
NetworkInterface.GetAllNetworkInterfaces()
来枚举NetworkInterfaces,但我不知道如何过滤出那些物理设备...NetworkInterface.GetAllNetworkInterfaces()
来枚举NetworkInterfaces,但我不知道如何过滤出那些物理设备...以“PCI”为前缀的网络接口(NI)是物理网络接口。
NetworkInterface[] fNetworkInterfaces = NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface adapter in fNetworkInterfaces)
{
string fRegistryKey = "SYSTEM\\CurrentControlSet\\Control\\Network\\{4D36E972-E325-11CE-BFC1-08002BE10318}\\" + adapter.Id + "\\Connection";
RegistryKey rk = Registry.LocalMachine.OpenSubKey(fRegistryKey, false);
if (rk != null)
{
string fPnpInstanceID = rk.GetValue("PnpInstanceID", "").ToString();
int fMediaSubType = Convert.ToInt32(rk.GetValue("MediaSubType", 0));
if (fPnpInstanceID.Length > 3 && fPnpInstanceID.Substring(0, 3) == "PCI")
{
}
}
}
public static void DisplayTypeAndAddress()
{
IPGlobalProperties computerProperties = IPGlobalProperties.GetIPGlobalProperties();
NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
Console.WriteLine("Interface information for {0}.{1} ",
computerProperties.HostName, computerProperties.DomainName);
foreach (NetworkInterface adapter in nics)
{
IPInterfaceProperties properties = adapter.GetIPProperties();
Console.WriteLine(adapter.Description);
Console.WriteLine(String.Empty.PadLeft(adapter.Description.Length,'='));
Console.WriteLine(" Interface type .......................... : {0}", adapter.NetworkInterfaceType);
Console.WriteLine(" Physical Address ........................ : {0}",
adapter.GetPhysicalAddress().ToString());
Console.WriteLine(" Minimum Speed............................ : {0}", adapter.Speed);
Console.WriteLine(" Is receive only.......................... : {0}", adapter.IsReceiveOnly);
Console.WriteLine(" Multicast................................ : {0}", adapter.SupportsMulticast);
Console.WriteLine();
}
}
你将不得不仔细查看所有提供的信息,然而,Win32_NetworkAdapterConfiguration 类将为您提供关于适配器配置的信息,例如 IP 地址等,而 Win32_NetworkAdapter 类则提供有关每个适配器的“静态”信息(最大速度、制造商等)。
string query = "SELECT * FROM Win32_NetworkAdapterConfiguration";
ManagementObjectSearcher moSearch = new ManagementObjectSearcher(query);
ManagementObjectCollection moCollection = moSearch.Get();// Every record in this collection is a network interface
foreach (ManagementObject mo in moCollection)
{
// ....
}