tags:

views:

66

answers:

2

I am building a C# application and I want to fetch the MAC ID of the system. I have found many code snippets, but they either give wrong answers or throw exceptions. I am not sure which code snippet is giving the right answer. Can someone provide me the exact code snippet that fetches the MAC ID?

+6  A: 

This will help you.

public string FetchMacId()
{
    string macAddresses = "";

    foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
    {
        if (nic.OperationalStatus == OperationalStatus.Up)
        {
            macAddresses += nic.GetPhysicalAddress().ToString();
            break;
        }
    }
    return macAddresses;
}
Pankaj Mishra
This one is great. It works fine for me. Thanks Pankaj
sumit_programmer
Why the string concatenation and the `break`? Why can’t you just write `return nic.GetPhysicalAddress().ToString()` inside the loop and get rid of the variable?
Timwi
A: 

System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces();

and iterate through each interface, getting the MAC address for each one.

Another way would be to use management object:

ManagementScope theScope = new ManagementScope("\\\\computerName\\root\\cimv2");
StringBuilder theQueryBuilder = new StringBuilder();
theQueryBuilder.Append("SELECT MACAddress FROM Win32_NetworkAdapter");
ObjectQuery theQuery = new ObjectQuery(theQueryBuilder.ToString());
ManagementObjectSearcher theSearcher = new ManagementObjectSearcher(theScope, theQuery);
ManagementObjectCollection theCollectionOfResults = theSearcher.Get();

foreach (ManagementObject theCurrentObject in theCollectionOfResults)
{
    string macAdd = "MAC Address: " + theCurrentObject["MACAddress"].ToString();
    MessageBox.Show(macAdd);
}
Nissim