获取特定 MAC 地址

Get Specific MAC Address

我的 VS2015 VB 应用正在读取用户计算机的 MAC 地址。这很有效,除了一些用户正在使用带有扩展坞的笔记本电脑,扩展坞会分配他们自己的 MAC 地址。我正在使用的代码 returns 它找到的第一个代码,可以搜索特定的代码吗?

    Dim mc As New ManagementClass(New ManagementPath("Win32_Processor"), New ObjectGetOptions(New ManagementNamedValueCollection()))
    Dim moc As ManagementObjectCollection = mc.GetInstances()

    mc.Path = New ManagementPath("Win32_NetworkAdapterConfiguration")

    moc = mc.GetInstances()

    Dim sMac As String = String.Empty

    For Each mo As ManagementObject In moc

        If (mo.GetPropertyValue("IPEnabled") = True) Then

            If (sMac = String.Empty) Then

                sMac = mo.GetPropertyValue("MacAddress").ToString()

            End If

        End If

    Next

此方法使用 System.Net.NetworkInformation.NetworkInterface 而不是直接查询 WMI 接口。

它 returns 所有当前网络接口的信息,除了 Loopback interface, where the Operational Status 是 UP。这通常会过滤 Teredo 和 ISATAP 接口,当然还有所有当前不活动的网络接口。

NetworkInterfaceType 也可用于过滤其他特定接口类型,例如 NetworkInterfaceType.Wireless80211

我提议这个 变体 因为它在需要时比 modify/expand 更简单。

NetInterfaceMac class 的每个实例提供:

  • 界面人性化描述
  • 接口的 IPV4 地址
  • 如果字符串格式为 MAC 地址 ("BF:D1:E8:8C:2B:A4")
  • MAC地址字节

Public Class NetInterfaceMac
    Public Property InterfaceDescription() As String
    Public Property IPAddress() As IPAddress
    Public Property MacAddress() As String
    Public Property MacAddressBytes() As Byte()
End Class

Public Shared Function GetNetworkMACAddresses() As List(Of NetInterfaceMac)
    Dim Macs As New List(Of NetInterfaceMac)()

    Dim NetInterfaces As NetworkInterface() = NetworkInterface.GetAllNetworkInterfaces()

    Macs.AddRange(NetInterfaces.Where(
        Function(ni) ni.NetworkInterfaceType <> NetworkInterfaceType.Loopback AndAlso
                     ni.OperationalStatus = OperationalStatus.Up).
        Select(Function(ni) New NetInterfaceMac() With {
            .IPAddress = ni.GetIPProperties().UnicastAddresses?.
                 Where(Function(ip) ip.IsDnsEligible = True)?.Select(Function(ip) ip.Address).ToArray(),
            .InterfaceDescription = ni.Description,
            .MacAddress = ni.GetPhysicalAddress().GetAddressBytes().
                Select(Function(b) b.ToString("X")).Aggregate(Function(s1, s2) s2 + ":" + s1),
            .MacAddressBytes = ni.GetPhysicalAddress().GetAddressBytes()
    }))

    Return Macs
End Function

调用示例:

Dim Macs As List(Of NetInterfaceMac) = GetNetworkMACAddresses()