Java-获取Linux系统的MAC地址

发布于 2024-11-19 05:11:25 字数 565 浏览 2 评论 0原文

我正在尝试使用以下代码获取 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();
}

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

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

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

秋意浓 2024-11-26 05:11:25

您可能有多个网络接口,我不会指望接口的名称。我建议您检查所有接口并查找具有 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();

    }

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:

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

    }
浅笑轻吟梦一曲 2024-11-26 05:11:25

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

From your comments, clearly network is 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)).

盗琴音 2024-11-26 05:11:25

只需对 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;
}

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

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

Just a small modification of the code of 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.

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文