Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formatting MAC address in C#

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?

like image 284
gln Avatar asked Sep 12 '11 06:09

gln


People also ask

How do I format a MAC address?

MAC addresses follow the format, XX:XX:XX:XX:XX:XX, but will sometimes display as XX-XX-XX-XX-XX-XX or XXXXXXXXXXXX.

What are the accepted formats of a MAC address?

Traditional MAC addresses are 12-digit (6 bytes or 48 bits) hexadecimal numbers. By convention, these addresses are usually written in one of the following three formats, although there are variations: MM:MM:MM:SS:SS:SS. MM-MM-MM-SS-SS-SS.

What are the 3 types of MAC address?

There are three types of MAC addresses: Unicast, Multicast, and Broadcast. The way to identify which address type you are viewing is simply look at the first byte. A unicast address's first byte will be even, like 02, 04, 06, etc. The first byte of a multicast address is odd, such as 01, 03, 05, etc.

What are the first 6 characters of a MAC address?

The Block ID is the first six characters of a MAC address. The Device ID is the remaining six characters. The Block ID is unique to the manufacturer. The Device ID is based on the device's model and manufacturer date.


2 Answers

try

mac = string.Join (":", (from z in nic.GetPhysicalAddress().GetAddressBytes() select z.ToString ("X2")).ToArray());
like image 55
Yahia Avatar answered Sep 20 '22 11:09

Yahia


The help for the command shows one way:

http://msdn.microsoft.com/en-us/library/system.net.networkinformation.physicaladdress.aspx

    PhysicalAddress address = adapter.GetPhysicalAddress();
    byte[] bytes = address.GetAddressBytes();
    for(int i = 0; i< bytes.Length; i++)
    {
        // Display the physical address in hexadecimal.
        Console.Write("{0}", bytes[i].ToString("X2"));
        // Insert a hyphen after each byte, unless we are at the end of the 
        // address.
        if (i != bytes.Length -1)
        {
             Console.Write("-");
        }
    }
    Console.WriteLine();
like image 37
Joe Avatar answered Sep 22 '22 11:09

Joe