Подтвердить что ты не робот

Форматирование MAC-адреса в С#

В моем приложении С# я хочу получить свой MAC-адрес с помощью класса NetworkInterface следующим образом:

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

Но этот код возвращает MAC без ':' или любого другого разделителя.

Как я могу получить MAC в этом формате: 88:88:88:88:87:88 , используя только код выше?

4b9b3361

Ответ 1

попробовать

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

Ответ 2

Справка для команды показывает один из способов:

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

Ответ 3

Использование комментария eFloh для использования BitConverter Я смог сделать следующее (предполагается, что mac предопределено как строка).

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

    //Do whatever else necessary with each mac...
}

Ответ 4

Если вы хотите показать это, вы должны это сделать:

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;
}

Ответ 5

Попробуйте что-то вроде этого:

// 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