侯体宗的博客
  • 首页
  • Hyperf版
  • beego仿版
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

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

苹果(mac/ios)  /  管理员 发布于 6年前   180

本文告诉大家如何在 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

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


  • 上一条:
    IOS正则表达式判断输入类型(整理)
    下一条:
    iOS 中使用正则表达式判断身份证格式及银行卡号格式是否正确(推荐)
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • 苹果将在iOS 18中启用“苹果账户”名称,“Apple ID”将成历史(0个评论)
    • 2023年国内最新注册苹果开发者账号之申请邓白氏编码流程步骤(0个评论)
    • 2023年国内最新注册苹果个人开发者账号及支付会员年费流程步骤(0个评论)
    • 2022年3月2号最新免费的苹果美国id账号分享-美区Apple ID共享(0个评论)
    • Objective-C的%s和%@(1个评论)
    • 近期文章
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(0个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 欧盟关于强迫劳动的规定的官方举报渠道及官方举报网站(0个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf文件功能(0个评论)
    • Laravel从Accel获得5700万美元A轮融资(0个评论)
    • 在go + gin中gorm实现指定搜索/区间搜索分页列表功能接口实例(0个评论)
    • 在go语言中实现IP/CIDR的ip和netmask互转及IP段形式互转及ip是否存在IP/CIDR(0个评论)
    • PHP 8.4 Alpha 1现已发布!(0个评论)
    • Laravel 11.15版本发布 - Eloquent Builder中添加的泛型(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2017-11
    • 2018-11
    • 2022-01
    • 2023-02
    • 2024-03
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客