0

I am using the following code to get the Client's Ip Address. But for all the headers, i am getting null value. And request.getRemoteAddr() returns IP address of the machine on which Tomcat server is running. So, what is the efficient way to get the IP address of the machine from which request is coming ?

    private static final String[] HEADERS_TO_TRY = { 
      "X-Forwarded-For",
      "Proxy-Client-IP",
      "WL-Proxy-Client-IP",
      "HTTP_X_FORWARDED_FOR",
      "HTTP_X_FORWARDED",
      "HTTP_X_CLUSTER_CLIENT_IP",
      "HTTP_CLIENT_IP",
      "HTTP_FORWARDED_FOR",
      "HTTP_FORWARDED",
      "HTTP_VIA",
      "REMOTE_ADDR" };

    public static String getClientIpAddress(HttpServletRequest request) {
      for (String header : HEADERS_TO_TRY) {
        String ip = request.getHeader(header);
        if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) {
            return ip;
        }
    }
    return request.getRemoteAddr();
   }
user3244519
  • 661
  • 5
  • 18
  • 36
  • 4
    Do you have a webserver or load balancer like Apache Http in between your servlet and the client? If so, you might have to configure that "proxy" to forward the client's ip, e.g. using the `HTTP_X` headers. – Thomas Aug 20 '14 at 11:19
  • possible duplicate of [Getting the client IP address: REMOTE\_ADDR, HTTP\_X\_FORWARDED\_FOR, what else could be useful?](http://stackoverflow.com/questions/527638/getting-the-client-ip-address-remote-addr-http-x-forwarded-for-what-else-coul) – Kumar Abhinav Aug 20 '14 at 11:21
  • @Thomas : There is no loadbalancer b/w client and servlet. I am running this servlet on Tomcat 6. – user3244519 Aug 20 '14 at 12:19
  • I definitely think what @Thomas has said is correct. IF you say you are getting the server address in request.getRemoteAddr(), definitely there is some proxy intercepting requests in that machine, – Ramesh PVK Aug 21 '14 at 20:41

0 Answers0