我需要打印机器的所有mac地址。建议的方法是使用NetworkInterface.getNetworkInterfaces()并迭代返回的枚举。但是,当某些设备关闭时(NO Ip已配置),则上述方法不会返回接口。
以下是我为测试目的编写的代码:
Enumeration<NetworkInterface> ni = NetworkInterface.getNetworkInterfaces();
while(ni.hasMoreElements()){
NetworkInterface nextElement = ni.nextElement();
byte[] mac = nextElement.getHardwareAddress();
if (mac != null) {
StringBuffer macAddress = new StringBuffer();
for (int i = 0; i < mac.length; i++) {
macAddress.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? ":" : ""));
}
System.out.println(macAddress.toString());
}
}
输出为: 00:03:B2:75:99:C3 (仅限G1)。
如果可能,我确实想要一个纯java解决方案。
有什么想法?
答案 0 :(得分:1)
看起来“ip addr”显示所有网络适配器,但并非所有网络适配器都配置了Internet地址。因此,Java只返回网络接口,即配置的适配器。