public static String mac_ip String arr= new String10; try EnumerationNetworkInterface networkInterfaces = NetworkInterfacegetNetworkInterfaces; while networkInte
这个错误可能是因为在调用 networkInterface.getHardwareAddress() 方法时返回了 null 值。这种情况可能发生在某些网络接口上,尤其是虚拟接口。
为了避免这个错误,您可以在调用 networkInterface.getHardwareAddress() 前添加一个 null 值检查。
以下是修改后的代码:
public static String[] mac_ip(){
String[] arr = new String[2]; // 只需要返回两个值,因此数组长度为 2
try {
Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
while (networkInterfaces.hasMoreElements()) {
NetworkInterface networkInterface = networkInterfaces.nextElement();
if (networkInterface.isUp() && !networkInterface.isLoopback()) {
Enumeration<InetAddress> addresses = networkInterface.getInetAddresses();
while (addresses.hasMoreElements()) {
InetAddress address = addresses.nextElement();
if (address.getHostAddress().contains(".")) {
arr[0] = address.getHostAddress();
byte[] mac = networkInterface.getHardwareAddress();
if (mac != null) { // 添加 null 值检查
StringBuilder sb = new StringBuilder();
for (int i = 0; i < mac.length; i++) {
sb.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : ""));
}
arr[1] = sb.toString();
}
break;
}
}
}
}
} catch (SocketException e) {
e.printStackTrace();
return arr;
}
return arr;
}
这样修改后,如果 networkInterface.getHardwareAddress() 返回 null 值,就不会再尝试访问它的长度,避免了空指针异常。
原文地址: https://www.cveoy.top/t/topic/bv66 著作权归作者所有。请勿转载和采集!