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

前端 未结 10 2066
刺人心
刺人心 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:07

    Why I think we should try to get IP from header 'X-Forwarded-For' first? If you get from request.getRemoteAddr(), it could be client's real ip or last proxy's ip which forwards the request. Thus we can't tell which condition it belongs to. However, if 'X-Forwarded-For' is set into the header, client ip is bound to be the left-most part of what you get from it.

        /**
         * Try to get real ip from request:
         * 
      *
    • try X-Forwarded-For
    • *
    • try remote address
    • *
    * * @param request request * @return real ip or "" */ private String tryGetRealIp(HttpServletRequest request) { // X-Forwarded-For: , , // If a request goes through multiple proxies, the IP addresses of each successive proxy is listed. // This means, the right-most IP address is the IP address of the most recent proxy and // the left-most IP address is the IP address of the originating client. String forwards = request.getHeader("X-Forwarded-For"); if (StringUtils.isNotBlank(forwards)) { // The left-most IP must be client ip String ip = StringUtils.substringBefore(forwards, ","); return ip; } else if (StringUtils.isNotBlank(request.getRemoteAddr())) { // this could be real client ip or last proxy ip which forwards the request return request.getRemoteAddr(); } return ""; }

提交回复
热议问题