Determine Network Adapter Type via WMI

后端 未结 3 977
盖世英雄少女心
盖世英雄少女心 2021-01-04 12:00

I\'m using WMI (Win32_NetworkAdapter) and trying to get the details of attached physical network adapters either wired or wireless and avoid virtual adapters, etc.

R

3条回答
  •  爱一瞬间的悲伤
    2021-01-04 12:24

    You can use new WMI class MSFT_NetAdapter in 'root\StandardCimv2' namespace. This class was introduced in Windows 8.

    We can use property ConnectorPresent to filter only to physical adapters. Next we must eliminate Wi-Fi adapters (which is present among physical adapters), we can use InterfaceType and/or NdisPhysicalMedium properties.

    InterfaceType is defined by the Internet Assigned Names Authority (IANA) and for all ethernet-like interfaces is value ethernetCsmacd (6) (see https://www.iana.org/assignments/ianaiftype-mib/ianaiftype-mib).

    In NdisPhysicalMedium is for ethernet adapters values 0 or 802.3 (14).

    So my solution for this in C# is:

    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
    }
    

提交回复
热议问题