How do I get the remote address of a client in servlet?

前端 未结 10 1901
刺人心
刺人心 2020-11-22 07:32

Is there any way that I could get the original IP address of the client coming to the server? I can use request.getRemoteAddr(), but I always seem to get the IP

10条回答
  •  有刺的猬
    2020-11-22 08:10

    The best solution I've ever used

    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;      
    } 
    

提交回复
热议问题