asp. net core sample method for getting MacAddress address

  • 2021-11-01 02:57:36
  • OfStack

This article shows you how to get the Mac address from dotnet core

Because dotnetcore is not directly related to hardware, it is impossible to obtain the Mac address of the current device by WMI

However, in dotnet core, you can use the following code to get all the network card addresses of this machine, including physical network card and virtual network card


IPGlobalProperties computerProperties = IPGlobalProperties.GetIPGlobalProperties();
   NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();

   Console.WriteLine("Interface information for {0}.{1}  ",
    computerProperties.HostName, computerProperties.DomainName);
   if (nics == null || nics.Length < 1)
   {
    Console.WriteLine(" No network interfaces found.");
    return;
   }

   Console.WriteLine(" Number of interfaces .................... : {0}", nics.Length);
   foreach (NetworkInterface adapter in nics)
   {
    Console.WriteLine();
    Console.WriteLine(adapter.Name + "," + adapter.Description);
    Console.WriteLine(String.Empty.PadLeft(adapter.Description.Length, '='));
    Console.WriteLine(" Interface type .......................... : {0}", adapter.NetworkInterfaceType);
    Console.Write(" Physical address ........................ : ");
    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();
   }

To run the code, here is the console


Interface information for lindexi.github
    Number of interfaces .................... : 6

    Hyper-V Virtual Ethernet Adapter #4
    ===================================
    Interface type .......................... : Ethernet
    Physical address ........................ : 00-15-5D-96-39-03

    Hyper-V Virtual Ethernet Adapter #3
    ===================================
    Interface type .......................... : Ethernet
    Physical address ........................ : 1C-1B-0D-3C-47-91

    Software Loopback Interface 1
    =============================
    Interface type .......................... : Loopback
    Physical address ........................ :

    Microsoft Teredo Tunneling Adapter
    ==================================
    Interface type .......................... : Tunnel
    Physical address ........................ : 00-00-00-00-00-00-00-E0

    Hyper-V Virtual Ethernet Adapter
    ================================
    Interface type .......................... : Ethernet
    Physical address ........................ : 5A-15-31-73-B0-9F

    Hyper-V Virtual Ethernet Adapter #2
    ===================================
    Interface type .......................... : Ethernet
    Physical address ........................ : 5A-15-31-08-13-B1

However, we can see that there are many network cards that do not need to be used. The method found from the stack network to obtain the current active ip network card can be judged whether it is a local roving network or not, and then whether there is a network


foreach (NetworkInterface adapter in nics.Where(c =>
    c.NetworkInterfaceType != NetworkInterfaceType.Loopback && c.OperationalStatus == OperationalStatus.Up))

Obtain whether the current network card has ip or ip is required


IPInterfaceProperties properties = adapter.GetIPProperties();

    var unicastAddresses = properties.UnicastAddresses;
    foreach (var temp in unicastAddresses.Where(temp =>
     temp.Address.AddressFamily == AddressFamily.InterNetwork))
    {
     //  This is the required network card 
    }

The simple output NIC uses adapter. GetPhysicalAddress (). ToString () output. If you need to output with connection, please use GetAddressBytes and output it yourself

The following code is extracted by me and can be used directly


public static void GetActiveMacAddress(string separator = "-")
  {
   NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();

   //Debug.WriteLine("Interface information for {0}.{1}  ",
   // computerProperties.HostName, computerProperties.DomainName);
   if (nics == null || nics.Length < 1)
   {
    Debug.WriteLine(" No network interfaces found.");
    return;
   }

   var macAddress = new List<string>();

   //Debug.WriteLine(" Number of interfaces .................... : {0}", nics.Length);
   foreach (NetworkInterface adapter in nics.Where(c =>
    c.NetworkInterfaceType != NetworkInterfaceType.Loopback && c.OperationalStatus == OperationalStatus.Up))
   {
    //Debug.WriteLine("");
    //Debug.WriteLine(adapter.Name + "," + adapter.Description);
    //Debug.WriteLine(string.Empty.PadLeft(adapter.Description.Length, '='));
    //Debug.WriteLine(" Interface type .......................... : {0}", adapter.NetworkInterfaceType);
    //Debug.Write(" Physical address ........................ : ");
    //PhysicalAddress address = adapter.GetPhysicalAddress();
    //byte[] bytes = address.GetAddressBytes();
    //for (int i = 0; i < bytes.Length; i++)
    //{
    // // Display the physical address in hexadecimal.
    // Debug.Write($"{bytes[i]:X2}");
    // // Insert a hyphen after each byte, unless we are at the end of the 
    // // address.
    // if (i != bytes.Length - 1)
    // {
    //  Debug.Write("-");
    // }
    //}

    //Debug.WriteLine("");

    //Debug.WriteLine(address.ToString());

    IPInterfaceProperties properties = adapter.GetIPProperties();

    var unicastAddresses = properties.UnicastAddresses;
    if (unicastAddresses.Any(temp => temp.Address.AddressFamily == AddressFamily.InterNetwork))
    {
     var address = adapter.GetPhysicalAddress();
     if (string.IsNullOrEmpty(separator))
     {
      macAddress.Add(address.ToString());
     }
     else
     {
      macAddress.Add(string.Join(separator, address.GetAddressBytes()));
     }
    }
   }
  }

The above method can be used not only in dotnet core, but also in dotnet framework, but also in dotnet framework through WMI

Using WMI to get MAC address method in dotnet framework


var managementClass = new ManagementClass("Win32_NetworkAdapterConfiguration");
     var managementObjectCollection = managementClass.GetInstances();
     foreach (var managementObject in managementObjectCollection.OfType<ManagementObject>())
     {
      using (managementObject)
      {
       if ((bool) managementObject["IPEnabled"])
       {
        if (managementObject["MacAddress"] == null)
        {
         return string.Empty;
        }

        return managementObject["MacAddress"].ToString().ToUpper();
       }
      }
     }

The output format is 5A: 15: 31: 73: B0: 9F and the output is a network card

NetworkInterface.GetPhysicalAddress Method (System.Net.NetworkInformation)

PhysicalAddress Class (System.Net.NetworkInformation)

c# - .NET Core 2.x how to get the current active local network IPv4 address? - Stack Overflow


Related articles: