asp.net core 获取 MacAddress 地址方法示例

 更新时间:2021年9月22日 10:01  点击:1481

本文告诉大家如何在 dotnet core 获取 Mac 地址

因为在 dotnetcore 是没有直接和硬件相关的,所以无法通过 WMI 的方法获取当前设备的 Mac 地址

但是在 dotnet core 可以使用下面的代码拿到本机所有的网卡地址,包括物理网卡和虚拟网卡

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

运行代码,下面是控制台

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

但是可以看到里面有很多不需要使用的网卡,从 堆栈 网找到的方法获取当前有活跃的 ip 的网卡可以通过先判断是不是本地巡回网络等,然后判断有没有网络

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

获取当前的网卡有没 ip 有 ip 才是需要的

IPInterfaceProperties properties = adapter.GetIPProperties();

    var unicastAddresses = properties.UnicastAddresses;
    foreach (var temp in unicastAddresses.Where(temp =>
     temp.Address.AddressFamily == AddressFamily.InterNetwork))
    {
     // 这个才是需要的网卡
    }

简单输出网卡使用 adapter.GetPhysicalAddress().ToString() 输出,如果需要输出带连接的请使用 GetAddressBytes 然后自己输出

下面的代码是我抽出来的,可以直接使用

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

上面的方法不仅是在 dotnet core 可以使用,在 dotnet framework 程序同样调用,但是在 dotnet framework 还可以通过 WMI 获取

在 dotnet framework 使用 WMI 获取 MAC 地址方法

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

输出的格式是 5A:15:31:73:B0:9F 同时输出是一个网卡

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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持猪先飞。

[!--infotagslink--]

相关文章

  • ASP.NET购物车实现过程详解

    这篇文章主要为大家详细介绍了ASP.NET购物车的实现过程,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...2021-09-22
  • .NET Core下使用Kafka的方法步骤

    这篇文章主要介绍了.NET Core下使用Kafka的方法步骤,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2021-09-22
  • 在ASP.NET 2.0中操作数据之七十二:调试存储过程

    在开发过程中,使用Visual Studio的断点调试功能可以很方便帮我们调试发现程序存在的错误,同样Visual Studio也支持对SQL Server里面的存储过程进行调试,下面就让我们看看具体的调试方法。...2021-09-22
  • 详解.NET Core 3.0 里新的JSON API

    这篇文章主要介绍了详解.NET Core 3.0 里新的JSON API,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2021-09-22
  • ASP.NET Core根据环境变量支持多个 appsettings.json配置文件

    这篇文章主要介绍了ASP.NET Core根据环境变量支持多个 appsettings.json配置文件,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2021-09-22
  • 记一次EFCore类型转换错误及解决方案

    这篇文章主要介绍了记一次EFCore类型转换错误及解决方案,帮助大家更好的理解和学习使用asp.net core,感兴趣的朋友可以了解下...2021-09-22
  • 详解ASP.NET Core 中基于工厂的中间件激活的实现方法

    这篇文章主要介绍了ASP.NET Core 中基于工厂的中间件激活的实现方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下...2021-09-22
  • asp.net通过消息队列处理高并发请求(以抢小米手机为例)

    这篇文章主要介绍了asp.net通过消息队列处理高并发请求(以抢小米手机为例),文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2021-09-22
  • Underscore源码分析

    Underscore 是一个 JavaScript 工具库,它提供了一整套函数式编程的实用功能,但是没有扩展任何 JavaScript 内置对象。这篇文章主要介绍了underscore源码分析相关知识,感兴趣的朋友一起学习吧...2016-01-02
  • ASP.NET单选按钮控件RadioButton常用属性和方法介绍

    RadioButton又称单选按钮,其在工具箱中的图标为 ,单选按钮通常成组出现,用于提供两个或多个互斥选项,即在一组单选钮中只能选择一个...2021-09-22
  • ASP.NET 2.0中的数据操作:使用两个DropDownList过滤的主/从报表

    在前面的指南中我们研究了如何显示一个简单的主/从报表, 该报表使用DropDownList和GridView控件, DropDownList填充类别,GridView显示选定类别的产品. 这类报表用于显示具有...2016-05-19
  • 详解.NET Core 使用HttpClient SSL请求出错的解决办法

    这篇文章主要介绍了.NET Core 使用HttpClient SSL请求出错的解决办法,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧...2021-09-22
  • ASP.NET中iframe框架点击左边页面链接 右边显示链接页面内容

    这篇文章主要介绍了ASP.NET中iframe框架点击左边页面链接,右边显示链接页面内容的实现代码,感兴趣的小伙伴们可以参考一下...2021-09-22
  • 创建一个完整的ASP.NET Web API项目

    ASP.NET Web API具有与ASP.NET MVC类似的编程方式,ASP.NET Web API不仅仅具有一个完全独立的消息处理管道,而且这个管道比为ASP.NET MVC设计的管道更为复杂,功能也更为强大。下面创建一个简单的Web API项目,需要的朋友可以参考下...2021-09-22
  • ASP.NET连接MySql数据库的2个方法及示例

    这篇文章主要介绍了ASP.NET连接MySql数据库的2个方法及示例,使用的是MySQL官方组件和ODBC.NET,需要的朋友可以参考下...2021-09-22
  • Asp.Net使用Bulk实现批量插入数据

    这篇文章主要介绍了Asp.Net使用Bulk实现批量插入数据的方法,对于进行asp.net数据库程序设计非常有借鉴价值,需要的朋友可以参考下...2021-09-22
  • 在ASP.NET 2.0中操作数据之二十九:用DataList和Repeater来显示数据

    本文主要讲解ASP.NET 2.0中如何使用DataList 和 Repeater 来呈现数据,DataList包含一个table标记,而Repeater不会添加任何额外的代码,个人在实际开发中更推荐使用Repeater。...2021-09-22
  • Asp.net中获取DataTable选择第一行某一列值

    这篇文章主要介绍了获取DataTable选择第一行某一列值,需要的朋友可以参考下...2021-09-22
  • ASP.Net中的async+await异步编程的实现

    这篇文章主要介绍了ASP.Net中的async+await异步编程的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2021-09-22
  • Asp.net动态生成html页面的方法分享

    这篇文章介绍了Asp.net动态生成html页面的方法,有需要的朋友可以参考一下...2021-09-22