如下代码所示,尽量排除非物理网卡返回第一个网卡的 mac 地址:

/**
     * 返回第一个匹配到的网卡的mac地址
     * 尽可能排除掉虚拟网卡
     *
     * @return String
     */
    public static String getMac() {
        try {
            Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
            while (networkInterfaces.hasMoreElements()) {
                NetworkInterface ni = networkInterfaces.nextElement();
                // 尽可能排除虚拟网卡、蓝牙网卡(以及其他非物理接口)
                String niName = ni.toString().toLowerCase();
                if (!ni.isVirtual() && !ni.isLoopback() && !niName.matches("^(?!.*(?:bluetooth|vm|vpn|virtual)).*$")) {
                    byte[] hardwareAddress = ni.getHardwareAddress();
                    if (hardwareAddress != null) {
                        StringBuilder sb = new StringBuilder();
                        for (int i = 0, j = hardwareAddress.length; i < j; i++) {
                            sb.append(String.format("%02X%s", hardwareAddress[i], (i < j - 1 ? "-" : "")));
                        }
                        return sb.toString().toUpperCase().trim();
                    }
                }
            }
        } catch (SocketException e) {
            return null;
        }
        return null;
    }

(END)