How to get Client's IP address in Java? Request.getRemoteAddr() returns IP address of the machine on which Tomcat server is running

扶醉桌前 提交于 2019-12-25 02:29:04

问题


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

来源:https://stackoverflow.com/questions/25403343/how-to-get-clients-ip-address-in-java-request-getremoteaddr-returns-ip-addre

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!