macos Java - 获取 Linux 系统的 MAC 地址

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6595479/
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-10-21 08:08:48  来源:igfitidea点击:

Java - Getting MAC address of Linux system

javamacoscrashmac-address

提问by y0u

I'm trying to get the MAC address of a linux system with this code:

我正在尝试使用以下代码获取 linux 系统的 MAC 地址:

try {
  ip = InetAddress.getLocalHost();
  NetworkInterface network = NetworkInterface.getByInetAddress(ip);
  byte[] mac = network.getHardwareAddress();
  // System.out.print("Current MAC address: ");
  for (int i = 0; i < mac.length; i++) {
    is = is + Integer.parseInt(
      String.format("%02X%s", mac[i], (i < mac.length - 1) ? "" : ""),16);
  }
} catch (UnknownHostException e) {
  e.printStackTrace();
} catch (SocketException e) {
  e.printStackTrace();
}

But it just crashes... does anyone know why?

但它只是崩溃了......有谁知道为什么?

采纳答案by Oliver Charlesworth

From your comments, clearly networkis null, which means that getByInetAddress()could not find an interface with that IP address (see the JavaDocs: http://download.oracle.com/javase/1.5.0/docs/api/java/net/NetworkInterface.html#getByInetAddress(java.net.InetAddress)).

从您的评论来看,显然networknull,这意味着getByInetAddress()找不到具有该 IP 地址的接口(请参阅 JavaDocs:http: //download.oracle.com/javase/1.5.0/docs/api/java/net/NetworkInterface。 html#getByInetAddress(java.net.InetAddress))。

回答by Guy

You might have more than one network interface and I would not count on the interface's name. I suggest you to go over all the interfaces and look for one that has a MAC address. You can use this example as a base line:

您可能有多个网络接口,而我不会指望接口的名称。我建议您检查所有接口并寻找具有 MAC 地址的接口。您可以将此示例用作基线:

try {

        Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
        while(networkInterfaces.hasMoreElements())
        {
            NetworkInterface network = networkInterfaces.nextElement();
            System.out.println("network : " + network);
            byte[] mac = network.getHardwareAddress();
            if(mac == null)
            {
                System.out.println("null mac");             
            }
            else
            {
                System.out.print("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());  
                break;
            }
        }
    } catch (SocketException e){

        e.printStackTrace();

    }

回答by TW2

Just a small modification of the code of Guy :

只是对 Guy 的代码稍作修改:

public String searchForMac() throws SocketException {
    String firstInterface = null;        
    Map<String, String> addressByNetwork = new HashMap<>();
    Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();

    while(networkInterfaces.hasMoreElements()){
        NetworkInterface network = networkInterfaces.nextElement();

        byte[] bmac = network.getHardwareAddress();
        if(bmac != null){
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < bmac.length; i++){
                sb.append(String.format("%02X%s", bmac[i], (i < bmac.length - 1) ? "-" : ""));        
            }

            if(sb.toString().isEmpty()==false){
                addressByNetwork.put(network.getName(), sb.toString());
                System.out.println("Address = "+sb.toString()+" @ ["+network.getName()+"] "+network.getDisplayName());
            }

            if(sb.toString().isEmpty()==false && firstInterface == null){
                firstInterface = network.getName();
            }
        }
    }

    if(firstInterface != null){
        return addressByNetwork.get(firstInterface);
    }

    return null;
}

This code has been tested on Windows, Linux (Ubuntu) and Mac OS X with success.

此代码已在 Windows、Linux (Ubuntu) 和 Mac OS X 上成功测试。

Because the network can be null, I ignore all null cases and I also ignore empty addresses. I think that if we don't do this, we view the crash. I choose the first found address and it works but it may be wrong, so just test it.

因为网络可以为空,所以我忽略所有空情况,也忽略空地址。我认为,如果我们不这样做,我们就会看到崩溃。我选择第一个找到的地址,它可以工作,但可能是错误的,所以只需测试它。