开发者社区> 问答> 正文

[@倚贤][¥20]springboot 如何获取客户端浏览器或者用户mac等唯一标识

目的是让用户登陆的时候和客户端设备绑定
网上获取ip的代码走不通 一直获取本地的

private String getIp(HttpServletRequest request) {

    String ipAddress = null;
    Enumeration<String> headerNames = request.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        String s = headerNames.nextElement();
        String header = request.getHeader(s);
        System.err.print(s+"=");
        System.err.println(header);
    }
    ipAddress = request.getHeader("x-forwarded-for");
    if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
        ipAddress = request.getHeader("Proxy-Client-IP");
    }
    if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
        //X-Real-IP:nginx服务代理
        ipAddress = request.getHeader("X-Real-IP");
    }
    if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
        ipAddress = request.getHeader("WL-Proxy-Client-IP");
    }
    if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {

        ipAddress = request.getHeader("HTTP_CLIENT_IP");
    }
    if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {

        ipAddress = request.getHeader("HTTP_X_FORWARDED_FOR");
    }
    if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
        ipAddress = request.getRemoteAddr();
        if (ipAddress.equals("127.0.0.1") || ipAddress.equals("0:0:0:0:0:0:0:1")) {
            // 根据网卡取本机配置的IP
            InetAddress inet = null;
            try {
                inet = InetAddress.getLocalHost();
            } catch (Exception e) {
                e.printStackTrace();
            }
            ipAddress = inet.getHostAddress();
        }

    }

    // 对于通过多个代理的情况,第一个IP为客户端真实IP,多个IP按照','分割
    if (ipAddress != null && ipAddress.length() > 15) { // "***.***.***.***".length()
        // = 15
        if (ipAddress.indexOf(",") > 0) {
            ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
        }
    }
    return ipAddress;
}

展开
收起
晓生寒 2018-12-10 22:58:15 7574 0
1 条回答
写回答
取消 提交回答
  • MAC地址需要前端使用JS来获取,如果浏览器没有带出来,服务端是无法获取的。

    2019-07-17 23:19:42
    赞同 1 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
WEB浏览器中即将发生的安全变化 立即下载
基于浏览器的实时构建探索之路 立即下载
基于浏览器的实时构建探索之路--玄寂 立即下载