获取特定的MAC地址

时间:2019-01-03 15:04:04

标签: vb.net

我的VS2015 VB应用正在读取用户计算机的MAC地址。除某些用户使用带有扩展坞的笔记本电脑外,该扩展坞分配了自己的MAC地址,此方法运行良好。我使用的代码返回找到的第一个代码,可以搜索特定代码吗?

    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

1 个答案:

答案 0 :(得分:1)

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

它返回除Loopback interface(其中Operational Status为UP)之外的所有当前网络接口的信息。通常,这通常会过滤Teredo和ISATAP接口,以及所有当前未激活的网络接口。

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

我提议使用此变体,因为在需要时修改/扩展起来更简单。

每个NetInterfaceMac类的实例都表示:

  • 界面人性化描述
  • 接口的IPV4地址
  • 如果是字符串格式("BF:D1:E8:8C:2B:A4"),则为MAC地址
  • 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()