Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mac Address format from string

Tags:

c#

    NetworkInterface[] arr = NetworkInterface.GetAllNetworkInterfaces();

    foreach (NetworkInterface item in arr)
    {
        PhysicalAddress mac = item.GetPhysicalAddress();
    }

It returns the value of 00E0EE00EE00 whereas I want it to display something like 00:E0:EE:00:EE:00 but i need to use .Net 4

any ideas ?

like image 773
user1710944 Avatar asked Dec 08 '12 06:12

user1710944


2 Answers

You can use String.Insert method of string class to add :

string macAddStr = "00E0EE00EE00";
string macAddStrNew = macAddStr;
int insertedCount = 0;
for(int i = 2; i < macAddStr.Length; i=i+2)  
   macAddStrNew = macAddStrNew.Insert(i+insertedCount++, ":");

//macAddStrNew will have address 00:E0:EE:00:EE:00
like image 62
Adil Avatar answered Oct 16 '22 22:10

Adil


I know this was answered a while ago, but I just wanted to clarify that the preferred solution is usually to create a reusable extension method for the PhysicalAddress class. Since it is a simple data class, and is likely not to change, this is better for reusability reasons. I will use Lorenzo's example because I like it the most, but you can use whichever routine suits you.

public static class PhysicalAddressExtensions
{
    public static string ToString(this PhysicalAddress address, string separator)
    {
        return string.Join(separator, address.GetAddressBytes()
                                             .Select(x => x.ToString("X2")))
    }
}

Now you can just use the extension method from now on like this:

NetworkInterface[] arr = NetworkInterface.GetAllNetworkInterfaces();

foreach (NetworkInterface item in arr)
{
    PhysicalAddress mac = item.GetPhysicalAddress();
    string stringFormatMac = mac.ToString(":");
}

Remember that the PhysicalAddress.Parse only accepts the RAW hex or dash separated values, in case you wanted to parse it back into an object. So stripping the separator character before you parse is important.

like image 41
Jeremy Avatar answered Oct 16 '22 21:10

Jeremy