java Servlet 取得遠端ip

原來不是這麼簡單

private static final String[] VALID_IP_HEADER_CANDIDATES = { 
  "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 : VALID_IP_HEADER_CANDIDATES) {
    String ipAddress = request.getHeader(header);
    if (ipAddress != null && ipAddress.length() != 0 && !"unknown".equalsIgnoreCase(ipAddress)) {
      return ipAddress;
    }
  }
  return request.getRemoteAddr();
}

發表迴響