Java获取客户端(浏览器)的MAC地址

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qing_mei_xiu/article/details/80745557

1.获取IP方式

public static String getIpAddress(HttpServletRequest request) {
        String ip = request.getHeader("X-real-ip");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("x-forwarded-for");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
}

2.通过IP获取Mac地址;

static String getMacAddrByIp(String ip) {
    String macAddr = null;
    try {
        Process process = Runtime.getRuntime().exec("nbtstat -a " + ip);
        BufferedReader br = new BufferedReader(
                new InputStreamReader(process.getInputStream()));
        Pattern pattern = Pattern.compile("([A-F0-9]{2}-){5}[A-F0-9]{2}");
        Matcher matcher;
        for (String strLine = br.readLine(); strLine != null;
             strLine = br.readLine()) {
            matcher = pattern.matcher(strLine);
            if (matcher.find()) {
                macAddr = matcher.group();
                break;
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    System.out.println(macAddr);
    return macAddr;
}


public static void main(String[] args) {
    String ip = "192.168.8.59";
    getMacAddrByIp(ip);
}

猜你喜欢

转载自blog.csdn.net/qing_mei_xiu/article/details/80745557