Tal*_* G. 5 java linux networking
我需要打印机器的所有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());
}
}
Run Code Online (Sandbox Code Playgroud)
输出为:00:03:B2:75:99:C3(仅G1).
如果可能,我确实想要一个纯java解决方案.
有什么想法吗 ?