Use Windows Management Instrumentation (WMI) to get a MAC Address
or Hard Drive Serial Number
A MAC address is a unique 48 bit number assigned to
each Network Interface Card (NIC) by its manufacturer. The MAC address can be
retrieved via VB.NET in a number of different ways. The easiest is to use
Windows Management Instrumentation (WMI) which provides access to
information about objects managed by Windows. With it you can enumerate all
disk drives, network adapters, processes, query all network connections that
are up, services that are paused etc.
To retrieve the MAC Address we can create a SQL query to be executed by the
System.Management namespace's ManagementObjectSearcher
object. To use the ManagementObjectSearcher, you will first need to set a
reference, in Solution Explorer, to the System.Management.dll.
The query will select all values (i.e. properties) from the Win32_NetworkAdapterConfiguration
WMI provider. By specifying a Where predicate of IPEnabled = True",
the query will only return the values for the active network card. This is
important since more than one network adapter may exist.
Results of the query run by the ManagementObjectSearcher's Get
method are returned as a ManagementObjectCollection.
Since our query retrieved all network adapter properties, we can loop through
the collection and extract the MAC Address.
Here is the VB.NET code to get the MAC address:
'
' Requires setting a reference to System.Management.dll
'
Imports System.Management
Try
Dim strMACAddress as string = ""
'
' Create the query, in SQL syntax, to retrieve the properties from
' the active Network Adapter.
'
Dim strQuery As String = _
"SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = True"
'
' Create a ManagementObjectSearcher object passing in the query to run.
'
Dim query As ManagementObjectSearcher = New ManagementObjectSearcher(strQuery)
'
' Create a ManagementObjectCollection assigning it the results of the query.
'
Dim queryCollection As ManagementObjectCollection = query.Get()
'
' Loop through the results extracting the MAC Address.
'
Dim mo As ManagementObject
For Each mo In queryCollection
strMACAddress = mo("MacAddress").ToString().Replace(":", "")
Exit For
Next
Return strMACAddress
Catch ex As Exception
Return ""
End Try
Similarly, you can get a wealth of information about your hard drives using WMI
by changing the query to retrieve information from the Win32_PhysicalMedia
provider.
Dim strSN as String = ""
Dim strQuery As String = "SELECT * FROM Win32_PhysicalMedia"
Dim query As ManagementObjectSearcher = New ManagementObjectSearcher(strQuery)
Dim queryCollection As ManagementObjectCollection = query.Get()
Dim mo As ManagementObject
For Each mo In queryCollection
strSN = mo("SerialNumber").ToString()
Next
This is just a small sample of the power of WMI and the ManagementObjectSearcher
class. You can poke around in Google or MSDN to learn how to use it to retrieve
tons of other information about your computer.
|