Prima aqui para ver este site na língua Portuguesa.

Get a MAC address in .NET

Fri, 15 Jul 2011

What to do if you want to get to a machine's MAC address in C# and Microsoft's myriad of classes are tripping you up

Here's a way to get the local machine's MAC address in C#. Note that there may be various MAC addresses (Ethernet cards, local loopback devices, hooked up 3G devices etc.), so we try to find only the Ethernet MAC address:

csharp
static string GetMacAddress()
{
  string macAddresses = "";
  foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
  {
    // Only consider Ethernet network interfaces, thereby ignoring any
    // loopback devices etc.
    if (nic.NetworkInterfaceType != NetworkInterfaceType.Ethernet) continue;
    if (nic.OperationalStatus == OperationalStatus.Up)
    {
      macAddresses += nic.GetPhysicalAddress().ToString();
      break;
    }
  }
  return macAddresses;
}