在一个项目中,客户端已将其服务器从CentOS6升级到CentOS7。在CentOS 6中,我们曾经从“ ifconfig -a”命令获取MAC地址,然后通过正则表达式(。[HWaddr。:(。*))提取MAC地址。现在在CentOS 7中,ifconfig不起作用。我们正在使用Java,建议使用下面的代码,效果很好,但是我们只能使用命令而不是使用Java API提供解决方案:
String getLocalServerMAC(){
String macAddress = null;
String macAddressToBeValidated = null;
try {
Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
for (NetworkInterface networkInterface : Collections.list(networkInterfaces)) {
if (networkInterface != null && networkInterface.isUp()) {
macAddressToBeValidated = getNotValidatedMACAddress(networkInterface);
if (macAddressToBeValidated != null && !macAddressToBeValidated.isEmpty()) {
macAddress = macAddressToBeValidated; break;
}
}
}
}catch (SocketException|RuntimeException e) {
LOGGER.error(e.getMessage(), e);
}
return macAddress;
}
private static String getNotValidatedMACAddress(NetworkInterface networkInterface) throws SocketException {
StringBuilder macAddressToBeValidated = new StringBuilder();
byte[] macAddressAsStream = networkInterface.getHardwareAddress();
if(macAddressAsStream != null) {
for (int i = 0; i < macAddressAsStream.length; i++){
macAddressToBeValidated.append(String.format("%02X%s", macAddressAsStream[i], (i < macAddressAsStream.length - 1) ? "-" : ""));
}
}
return macAddressToBeValidated.toString();
}