系统相关
首页 > 系统相关> > Java – 获取Linux系统的MAC地址

Java – 获取Linux系统的MAC地址

作者:互联网

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

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

解决方法:

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

标签:java,crash,macos,mac-address
来源: https://codeday.me/bug/20190716/1482630.html