The Haunted House

Friday, August 03, 2007

How to get your Mac address with C#

The other night I was playing around with some code and I need to be able to extract the users MAC address for their machine. A MAC address is a number that uniquely identifies your network adapter in your machine. This can be achieved by using the ManagementClass from the System.Management namespace in .NET. The members of the ManagementClass enable you to access WMI data using a specific WMI class path. More information on the Win32 classes accessed via WMI can be found here. This example uses the WIN32_NetworkAdapter part of WMI. More information about data passed back can be found here.

The code below is all you need to extract the MAC Address. You will need to include a reference to the System.Management assembly in your project.

private string GetMacAddress()
{
ManagementClass managementClass =
new ManagementClass("Win32_NetworkAdapterConfiguration");


ManagementObjectCollection managementObjectCollection
= managementClass.GetInstances();


foreach (ManagementObject mo in managementObjectCollection)
{
if ((bool)mo["IPEnabled"] == true)
{
return mo["MacAddress"].ToString();
}
}


return string.Empty;
}


Labels:

0 Comments:

Post a Comment

<< Home