首頁 > 硬體

java如何獲取使用者端真正的ip地址

2020-10-13 16:08:40

java獲取使用者端真實IP

獲得使用者端真實IP地址的方法一

  • 01

    public String getRemortIP(HttpServletRequest request) {
    if (request.getHeader("x-forwarded-for") == null) {
    return request.getRemoteAddr();
    }
    return request.getHeader("x-forwarded-for");
    }

  • End

獲得使用者端真實IP地址的方法二

  • 01

    public String getIpAddr(HttpServletRequest request) {
    String 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.getRemoteAddr();
    }
    return ip;
    }

  • End

特別提示

可是,如果通過了多級反向代理的話,X-Forwarded-For的值並不止一個,而是一串IP值,究竟哪個才是真正的使用者端的真實IP呢? 答案是取X-Forwarded-For中第一個非unknown的有效IP字串。如: X-Forwarded-For:192.168.1.110, 192.168.1.120, 192.168.1.130, 192.168.1.100 使用者真實IP為: 192.168.1.110


IT145.com E-mail:sddin#qq.com