当前位置: 移动技术网 > IT编程>开发语言>.net > asp.net core 获取 MacAddress 地址方法示例

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

2019年03月20日  | 移动技术网IT编程  | 我要评论

3u8888,非常了得康逸琨,绝代野仙

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

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

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网