Formatting MAC address in C#

眉间皱痕 提交于 2019-11-27 23:36:43

try

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

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();
Jon Peterson

Using the comment by eFloh for using BitConverter I was able to do the following (assuming mac is predefined as a string).

foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
{
    mac = BitConverter.ToString(nic.GetPhysicalAddress().GetAddressBytes()).Replace('-', ':');

    //Do whatever else necessary with each mac...
}
H-JOSUE

Where you want to show that, you have to do this:

txtMac.text=getFormatMac(GetMacAddress());
public string GetMacAddress()

{
    NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
    String sMacAddress = string.Empty;
    foreach (NetworkInterface adapter in nics)
    {
         if (sMacAddress == String.Empty)// solo retorna la mac de la primera tarjeta
         {
              IPInterfaceProperties properties = adapter.GetIPProperties();
              sMacAddress = adapter.GetPhysicalAddress().ToString();
          }
    }
    return sMacAddress;
}

public string getFormatMac(string sMacAddress)
{
    string MACwithColons = "";
    for (int i = 0; i < macName.Length; i++)
    {
        MACwithColons = MACwithColons + macName.Substring(i, 2) + ":";
        i++;
    }
    MACwithColons = MACwithColons.Substring(0, MACwithColons.Length - 1);

    return MACwithColons;
}

Pabinator

Try Something like this:

// Insert Colons on MAC
string MACwithColons = "";
for (int i = 0; i < MAC.Length; i++) {
  MACwithColons = MACwithColons + MAC.Substring(i, 2) + ":";
  i++;
}
MACwithColons = MACwithColons.Substring(0, MACwithColons.Length - 1); // Remove the last colon
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!