用Java获取系统的MAC地址

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16448995/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-16 06:58:32  来源:igfitidea点击:

Get MAC Address of System in Java

java

提问by Veer Shrivastav

I need to get the mac address of the system running the program. But I am not able to do that.

我需要获取运行程序的系统的mac地址。但我不能那样做。

I am writing following code:

我正在编写以下代码:

public class App{

       public static void main(String[] args){

        InetAddress ip;
        try {

            ip = InetAddress.getLocalHost();
            System.out.println("Current IP address : " + ip.getHostAddress());

            NetworkInterface network = NetworkInterface.getByInetAddress(ip);

            byte[] mac = network.getHardwareAddress();

            System.out.print("Current MAC address : ");

            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < mac.length; i++) {
                sb.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : ""));        
            }
            System.out.println(sb.toString());

        } catch (UnknownHostException e) {

            e.printStackTrace();

        } catch (SocketException e){

            e.printStackTrace();

        }

       }

    }

And I am getting following results:

我得到以下结果:

 Current IP address : 14.96.192.202
 Current MAC address : 

I am not getting the MAC Address it is blank.

我没有得到 MAC 地址,它是空白的。

I saw this example from here

我从这里看到了这个例子

采纳答案by Jason Sperske

If you account for multiple interfaces, and some null MAC addresses (I'm running Java 7 on Windows 7 with VMWare installed (so I have some virtual network adapters)) then this code seems to work:

如果您考虑了多个接口和一些空 MAC 地址(我在安装了 VMWare 的 Windows 7 上运行 Java 7(所以我有一些虚拟网络适配器)),那么此代码似乎有效:

public static void main(String[] args) {
  try {
    InetAddress ip = InetAddress.getLocalHost();
    System.out.println("Current IP address : " + ip.getHostAddress());

    Enumeration<NetworkInterface> networks = NetworkInterface.getNetworkInterfaces();
    while(networks.hasMoreElements()) {
      NetworkInterface network = networks.nextElement();
      byte[] mac = network.getHardwareAddress();

      if(mac != null) {
        System.out.print("Current MAC address : ");

        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < mac.length; i++) {
          sb.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : ""));
        }
        System.out.println(sb.toString());
      }
    }
  } catch (UnknownHostException e) {
    e.printStackTrace();
  } catch (SocketException e){
    e.printStackTrace();
  }
}

Here is (a sanitized version of) what I see on my computer when I run it:

这是我运行时在计算机上看到的(经过消毒的版本):

Current IP address : {I'm not telling :)}
Current MAC address : 
Current MAC address : {actual hardware interface}
Current MAC address : 00-00-00-00-00-00-00-E0
Current MAC address : 00-00-00-00-00-00-00-E0
Current MAC address : 00-00-00-00-00-00-00-E0
Current MAC address : 00-00-00-00-00-00-00-E0
Current MAC address : 00-00-00-00-00-00-00-E0
Current MAC address : 00-50-56-C0-00-01
Current MAC address : 00-50-56-C0-00-08

And here is the output of running ipconfig /all

这是运行的输出 ipconfig /all

C:\>ipconfig /all

Windows IP Configuration (minus any actual interface because I don't like sharing that kind of information :)

Ethernet adapter Local Area Connection 2:

   Media State . . . . . . . . . . . : Media disconnected
   Connection-specific DNS Suffix  . :
   Description . . . . . . . . . . . : Gbridge Virtual Private Network Adapter
   Physical Address. . . . . . . . . : 02-50-F2-CE-82-01
   DHCP Enabled. . . . . . . . . . . : Yes
   Autoconfiguration Enabled . . . . : Yes

Ethernet adapter VMware Network Adapter VMnet1:

   Connection-specific DNS Suffix  . :
   Description . . . . . . . . . . . : VMware Virtual Ethernet Adapter for VMnet1
   Physical Address. . . . . . . . . : 00-50-56-C0-00-01
   DHCP Enabled. . . . . . . . . . . : No
   Autoconfiguration Enabled . . . . : Yes
   Link-local IPv6 Address . . . . . : fe80::9c27:3d03:da2c:f14d%19(Preferred)
   Autoconfiguration IPv4 Address. . : {Hidden}(Preferred)
   Subnet Mask . . . . . . . . . . . : 255.255.0.0
   Default Gateway . . . . . . . . . :
   DHCPv6 IAID . . . . . . . . . . . : 268456022
   DHCPv6 Client DUID. . . . . . . . : 00-01-00-01-13-DB-D9-CB-B8-AC-6F-AF-9D-F2
   DNS Servers . . . . . . . . . . . : fec0:0:0:ffff::1%1
                                       fec0:0:0:ffff::2%1
                                       fec0:0:0:ffff::3%1
   NetBIOS over Tcpip. . . . . . . . : Enabled

Ethernet adapter VMware Network Adapter VMnet8:

   Connection-specific DNS Suffix  . :
   Description . . . . . . . . . . . : VMware Virtual Ethernet Adapter for VMnet8
   Physical Address. . . . . . . . . : 00-50-56-C0-00-08
   DHCP Enabled. . . . . . . . . . . : No
   Autoconfiguration Enabled . . . . : Yes
   Link-local IPv6 Address . . . . . : fe80::cdbb:434:7fd9:2574%20(Preferred)
   IPv4 Address. . . . . . . . . . . : 192.168.42.1(Preferred)
   Subnet Mask . . . . . . . . . . . : 255.255.255.0
   Default Gateway . . . . . . . . . :
   DHCPv6 IAID . . . . . . . . . . . : 285233238
   DHCPv6 Client DUID. . . . . . . . : 00-01-00-01-13-DB-D9-CB-B8-AC-6F-AF-9D-F2
   DNS Servers . . . . . . . . . . . : fec0:0:0:ffff::1%1
                                       fec0:0:0:ffff::2%1
                                       fec0:0:0:ffff::3%1
   NetBIOS over Tcpip. . . . . . . . : Enabled

Tunnel adapter 6TO4 Adapter:

   Description . . . . . . . . . . . : Microsoft 6to4 Adapter
   Physical Address. . . . . . . . . : 00-00-00-00-00-00-00-E0
   DHCP Enabled. . . . . . . . . . . : No
   Autoconfiguration Enabled . . . . : Yes
   IPv6 Address. . . . . . . . . . . : 2002:204c:1bc6::204c:1bc6(Preferred)
   Default Gateway . . . . . . . . . :
   NetBIOS over Tcpip. . . . . . . . : Disabled

Tunnel adapter isatap.{3E45CB42-BC1E-4F89-9C16-25166C0EABA1}:

   Media State . . . . . . . . . . . : Media disconnected
   Connection-specific DNS Suffix  . :
   Description . . . . . . . . . . . : Microsoft ISATAP Adapter
   Physical Address. . . . . . . . . : 00-00-00-00-00-00-00-E0
   DHCP Enabled. . . . . . . . . . . : No
   Autoconfiguration Enabled . . . . : Yes

Tunnel adapter isatap.{77F1FADC-02BA-44AF-9FDF-97E23F8B5FE7}:

   Media State . . . . . . . . . . . : Media disconnected
   Connection-specific DNS Suffix  . :
   Description . . . . . . . . . . . : Microsoft ISATAP Adapter #3
   Physical Address. . . . . . . . . : 00-00-00-00-00-00-00-E0
   DHCP Enabled. . . . . . . . . . . : No
   Autoconfiguration Enabled . . . . : Yes

Tunnel adapter isatap.{608257AC-C0F3-43A5-8595-898533C95D90}:

   Media State . . . . . . . . . . . : Media disconnected
   Connection-specific DNS Suffix  . :
   Description . . . . . . . . . . . : Microsoft ISATAP Adapter #5
   Physical Address. . . . . . . . . : 00-00-00-00-00-00-00-E0
   DHCP Enabled. . . . . . . . . . . : No
   Autoconfiguration Enabled . . . . : Yes

The challenge in getting "just one value" from this mess comes from the relationship between InetAddress.getLocalHost().getHostAddress()and the network interfaces themselves. Consider this slight expanded version of the initial program (using this really cool IterableEnumerationutility class):

从这种混乱中获得“只有一个价值”的挑战来自InetAddress.getLocalHost().getHostAddress()网络接口和网络接口本身之间的关系。考虑一下初始程序的这个稍微扩展的版本(使用这个非常酷的IterableEnumeration实用程序类):

public static void main(String[] args) throws UnknownHostException, SocketException {
  System.out.println("Current IP address : " + InetAddress.getLocalHost().getHostAddress());

  for(NetworkInterface network : IterableEnumeration.make(NetworkInterface.getNetworkInterfaces())) {
    byte[] mac = network.getHardwareAddress();
    if(mac != null) {
      System.out.print("Current MAC address : ");
      StringBuilder sb = new StringBuilder();
      for (int i = 0; i < mac.length; i++) {
        sb.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : ""));
      }
      System.out.println(sb.toString());
      //Bound InetAddress for interface
      for(InetAddress address : IterableEnumeration.make(network.getInetAddresses())) {
        System.out.println("\tBound to:"+address.getHostAddress());
      }
    }
  }
}

If you run this on your computer you will see your current IP address correlates to one adapter but that MAC address of your hardware interface sees it's self as a different IP address. Maybe you can filter out virtual addresses or just find a way to utilize all available addresses.

如果您在您的计算机上运行它,您将看到您当前的 IP 地址与一个适配器相关联,但您的硬件接口的 MAC 地址将其自身视为不同的 IP 地址。也许您可以过滤掉虚拟地址,或者只是想办法利用所有可用地址。