Reputation: 684
I have tried to get the MAC address of each network interface card on a machine by using the below function in VB.NET, but I just realized that this function doesn't work in Windows XP:
Function getMacAddress()
Dim nics() As NetworkInterface = NetworkInterface.GetAllNetworkInterfaces()
Return nics(1).GetPhysicalAddress.ToString
End Function
How can I make this code to run on Windows XP? What other alternatives exist to get the list of MAC addresses on Windows XP?
Upvotes: 2
Views: 22773
Reputation: 975
I did some digging when connecting to different VPNs. So far the below seems pretty reliable. Relying on 0 or 1 for the actual physical adapter as suggested above does not work in many cases. In some cases my actual Ethernet adapter was the 3rd adapter. Excluding the loopbacks, tunnels, and ppp adapters should narrow it down. I found that many of my non physical adapters have the string "00000000000000E0" as the mac address.
Private Function getMacAddress() As String
Try
Dim adapters As NetworkInterface() = NetworkInterface.GetAllNetworkInterfaces()
Dim adapter As NetworkInterface
Dim myMac As String = String.Empty
For Each adapter In adapters
Select Case adapter.NetworkInterfaceType
'Exclude Tunnels, Loopbacks and PPP
Case NetworkInterfaceType.Tunnel, NetworkInterfaceType.Loopback, NetworkInterfaceType.Ppp
Case Else
If Not adapter.GetPhysicalAddress.ToString = String.Empty And Not adapter.GetPhysicalAddress.ToString = "00000000000000E0" Then
myMac = adapter.GetPhysicalAddress.ToString
Exit For ' Got a mac so exit for
End If
End Select
Next adapter
Return myMac
Catch ex As Exception
Return String.Empty
End Try
End Function
Upvotes: 2
Reputation: 10931
Works for me on XP, except I've got a few interfaces and my first (0th) is my "real" MAC address, and it corresponds to the MAC address reported by a non-.NET program.
Upvotes: 1