Sco*_*ttN 10 .net c# wmi wmi-query
我正在使用WMI(Win32_NetworkAdapter)并尝试获取有线或无线连接的物理网络适配器的详细信息,并避免使用虚拟适配器等.
阅读本文后,它解释了您必须对WMI进行一些巧妙的查询以消除虚拟适配器并尝试仅返回真正的物理适配器.
阅读这篇文章,它解释了你可以比较网络适配器"描述"中的文字,看看它是否包括"无线","802.11"或"WLAN",如果是,那么很可能适配器是无线的适配器.
对于今天的.Net版本和其他改进,这些真的是在Windows XP +上确定网络适配器是有线还是无线并且不是来自VM软件等的虚拟适配器的唯一两种方式?如果没有,请解释.
您可以在“root\StandardCimv2”命名空间中使用新的 WMI 类MSFT_NetAdapter。此类是在Windows 8中引入的。
我们可以使用属性ConnectorPresent来仅过滤物理适配器。接下来,我们必须消除 Wi-Fi 适配器(存在于物理适配器中),我们可以使用InterfaceType和/或NdisPhysicalMedium属性。
InterfaceType由互联网名称分配机构 (IANA) 定义,对于所有类似以太网的接口,其值为ethernetCsmacd (6)(请参阅https://www.iana.org/assignments/ianaiftype-mib/ianaiftype-mib)。
在NdisPhysicalMedium中,以太网适配器的值为0或802.3 (14)。
所以我在 C# 中的解决方案是:
try
{
var objectSearcher = new ManagementObjectSearcher("root\\StandardCimv2", $@"select Name, InterfaceName, InterfaceType, NdisPhysicalMedium from MSFT_NetAdapter where ConnectorPresent=1"); //Physical adapter
int count = 0;
foreach (var managementObject in objectSearcher.Get())
{
//The locally unique identifier for the network interface. in InterfaceType_NetluidIndex format. Ex: Ethernet_2.
string interfaceName = managementObject["InterfaceName"]?.ToString();
//The interface type as defined by the Internet Assigned Names Authority (IANA).
//https://www.iana.org/assignments/ianaiftype-mib/ianaiftype-mib
UInt32 interfaceType = Convert.ToUInt32(managementObject["InterfaceType"]);
//The types of physical media that the network adapter supports.
UInt32 ndisPhysicalMedium = Convert.ToUInt32(managementObject["NdisPhysicalMedium"]);
if (!string.IsNullOrEmpty(interfaceName) &&
interfaceType == 6 && //ethernetCsmacd(6) --for all ethernet-like interfaces, regardless of speed, as per RFC3635
(ndisPhysicalMedium == 0 || ndisPhysicalMedium == 14)) //802.3
{
count++;
}
}
return count;
}
catch (ManagementException)
{
//Run-time requirements WMI MSFT_NetAdapter class is included in Windows 8 and Windows Server 2012
}
Run Code Online (Sandbox Code Playgroud)
我发现这是一个老问题,但我在互联网上的其他地方找到了答案,其中描述了如何做到这一点(一直向下滚动到评论)。
评论者的技术允许识别 WiFi 和蓝牙接口,其中所有其他类型可以分组在一起。如果目标只是将 WiFi 与以太网适配器分开,那应该就足够了。
查询是(Powershell 示例):
$nics = Get-WmiObject -Namespace "root/CIMV2" -Query "SELECT * FROM Win32_NetworkAdapter"
$types = Get-WmiObject -Namespace "root/WMI" -Query "SELECT * FROM MSNdis_PhysicalMediumType"
Run Code Online (Sandbox Code Playgroud)
第一个查询是提供适配器列表的常用方法。如前所述,可以通过许多其他选择标准将其过滤为仅包括有效的物理设备。
第二个查询返回一个带有NdisPhysicalMediumType属性的 WMI 对象,根据链接站点,该属性的值为9(表示 WiFi)、10(表示蓝牙)、0(表示以太网和大多数其他适配器类型)。
看起来必须使用第一个查询的Nameor属性和第二个查询的属性在脚本中手动完成这两个查询的连接。DescriptionInstanceName