如何使用终端而不使用网卡在CentOS 7中获取MAC地址?

问题描述 投票:0回答:2

在一个项目中,客户端已将其服务器从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();
}
linux centos7 mac-address
2个回答
0
投票

ifconfig已过时-为什么不解析ip link show的输出?


0
投票

如何使用命令ip link?或者,如果您知道您的ip addres,也可以这样做。

© www.soinside.com 2019 - 2024. All rights reserved.