tags:

views:

109

answers:

6

Hey, I have found this code to get a MAC address, but it returns a long string and doesn't include ':'.

Is it possible to add in the ':' or split up the string and add it it myself?

here is the code:

private object GetMACAddress()
{
    string macAddresses = "";

    foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
    {
        if (nic.OperationalStatus == OperationalStatus.Up)
        {
            macAddresses += nic.GetPhysicalAddress().ToString();
            break;
        }
    }

    return macAddresses;
 }

It returns the value of 00E0EE00EE00 whereas I want it to display something like 00:E0:EE:00:EE:00.

Any ideas?

Thanks.

A: 

Use the GetAddressBytes method:

    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("-");
        }
    }
Sjoerd
address does not exist in the current context?
Crazyd22
It is an example. Obviously you have to replace the `address` variable with the variable you are using.
Sjoerd
A: 
function string GetSplitedMacAddress(string macAddresses)
{
    for (int Idx = 2; Idx <= 15; Idx += 3)
    {
        macAddresses = macAddresses.Insert(Idx, ":");
    }

    return macAddresses;
}
Svisstack
This doesn't work, returns the same value
Crazyd22
this work i tested and result is 00:E0:EE:00:EE:00
Svisstack
+3  A: 

i am using following code to access mac address in format you want :

public string GetSystemMACID()
        {
            string systemName = System.Windows.Forms.SystemInformation.ComputerName;
            try
            {
                ManagementScope theScope = new ManagementScope("\\\\" + Environment.MachineName + "\\root\\cimv2");
                ObjectQuery theQuery = new ObjectQuery("SELECT * FROM Win32_NetworkAdapter");
                ManagementObjectSearcher theSearcher = new ManagementObjectSearcher(theScope, theQuery);
                ManagementObjectCollection theCollectionOfResults = theSearcher.Get();

                foreach (ManagementObject theCurrentObject in theCollectionOfResults)
                {
                    if (theCurrentObject["MACAddress"] != null)
                    {
                        string macAdd = theCurrentObject["MACAddress"].ToString();
                        return macAdd.Replace(':', '-');
                    }
                }
            }
            catch (ManagementException e)
            {
                           }
            catch (System.UnauthorizedAccessException e)
            {

            }
            return string.Empty;
        }
Pranay Rana
does this give a reliable MAC address? Because I had the problem of getting virtual ones.
Crazyd22
yes its working for me
Pranay Rana
Yeah works perfect, thanks!
Crazyd22
As for me I always try to avoid WMI magic when there are any managed alternatives.
Regent
+4  A: 

You can use the BitConverter.ToString() method:

var hex = BitConverter.ToString( nic.GetPhysicalAddress().GetAddressBytes() );
hex.Replace( "-", ":" );
tanascius
Best solution for me...
Paja
A: 

You can use this code (uses LINQ):

using System.Linq;
using System.Net;
using System.Net.NetworkInformation;

// ....

private static string GetMACAddress()
{
    foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
    {
        if (nic.OperationalStatus == OperationalStatus.Up)
            return AddressBytesToString(nic.GetPhysicalAddress().GetAddressBytes());
    }

    return string.Empty;
}

private static string AddressBytesToString(byte[] addressBytes)
{
    return string.Join(":", (from b in addressBytes
                             select b.ToString("X2")).ToArray());
}
Paja
+2  A: 

Using LINQ just replace

macAddresses += nic.GetPhysicalAddress().ToString();
// Produces "00E0EE00EE00"

with

macAddresses += String.Join(":", nic.GetPhysicalAddress()
                                    .GetAddressBytes()
                                    .Select(b => b.ToString("X2"))
                                    .ToArray());
// Produces "00:E0:EE:00:EE:00"

You can also play with ToString parameter, for instance if you like 00:e0:ee:00:ee:00 more than 00:E0:EE:00:EE:00 then you can just pass "x2" instead of "X2".

Regent
You might want a .ToArray() after the .Select() to make it compile.
Andrew
@Andrew: Thank you, originally I used .NET 4.0 where `String.Join` have overload accepting `IEnumerable<string>` argument.Updated my code to include `.ToArray()`
Regent