如何用Java获取客户端的IP地址? Request.getRemoteAddr()返回运行Tomcat服务器的计算机的IP地址

时间:2014-08-20 11:17:33

标签: java java-ee networking http-headers ip

我使用以下代码获取客户端的IP地址。但对于所有标题,我得到空值。 request.getRemoteAddr()返回运行Tomcat服务器的计算机的IP地址。那么,获取请求来自的机器的IP地址的有效方法是什么?

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

0 个答案:

没有答案