Formatting MAC address in C#

gln picture gln · Sep 12, 2011 · Viewed 23.1k times · Source

In my C# application, I want to get my MAC address by using NetworkInterface class as the following:

NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces()
{
    mac = nic.GetPhysicalAddress()
}

But this code returns the MAC without ':' or any other separator.

How can I retrieve the MAC in this format: 88:88:88:88:87:88 using the code above ONLY?

Answer

Yahia picture Yahia · Sep 12, 2011

try

mac = string.Join (":", (from z in nic.GetPhysicalAddress().GetAddressBytes() select z.ToString ("X2")).ToArray());