15

I am curious if there is any library that handles already this kind of stuff, or I have to do it by myself once again. So, the thing is I want to get IP address field from the visitors HTTP header request on my server, and do the whole thing in Java? Any help would be nice. Thanks in advance.

4

2 回答 2

35

Use the getHeader(String Name) method of the javax.servlet.http.HttpServletRequest object to retrieve the value of Remote_Addr variable. Here is the sample code:

String ipAddress = request.getHeader("Remote_Addr");

If this code returns empty string, then use this way:

String ipAddress = request.getHeader("HTTP_X_FORWARDED_FOR");

if (ipAddress == null) {
    ipAddress = request.getRemoteAddr();
}
于 2012-04-28T11:33:54.080 回答
10

即使有一个被高度支持的公认答案,我还是想提出一个替代方案并指出公认答案的缺点。

request.getHeader("Remote_Addr")指定返回与完全相同request.getRemoteAddr()。因此,两者都检查是没有意义的。另请注意,这getRemoteAddr是一种javax.servlet.ServletRequest(即与 HTTP 无关的)whilegetHeader方法javax.servlet.http.HttpServletRequest

此外,一些代理使用Client-IP而不是X-Forwarded-For. 有关讨论,请参阅https://stackoverflow.com/a/7446010/131929

我不知道使用HTTP_X_FORWARDED_FORoverX-Forwarded-For的可靠性如何。在 Java 中,我宁愿使用直接的简短形式。有关讨论,请参阅https://stackoverflow.com/a/3834169/131929。大写/小写没有区别,因为getHeader指定为区分大小写

Java 替代方案

public final class ClientIpAddress {

  // CHECKSTYLE:OFF
  // https://stackoverflow.com/a/11327345/131929
  private static Pattern PRIVATE_ADDRESS_PATTERN = Pattern.compile(
      "(^127\\.)|(^192\\.168\\.)|(^10\\.)|(^172\\.1[6-9]\\.)|(^172\\.2[0-9]\\.)|(^172\\.3[0-1]\\.)|(^::1$)|(^[fF][cCdD])",
      Pattern.CANON_EQ);
  // CHECKSTYLE:ON

  private ClientIpAddress() {
  }

  /**
   * Extracts the "real" client IP address from the request. It analyzes request headers
   * {@code REMOTE_ADDR}, {@code X-Forwarded-For} as well as {@code Client-IP}. Optionally
   * private/local addresses can be filtered in which case an empty string is returned.
   *
   * @param request HTTP request
   * @param filterPrivateAddresses true if private/local addresses (see
   * https://en.wikipedia.org/wiki/Private_network#Private_IPv4_address_spaces and
   * https://en.wikipedia.org/wiki/Unique_local_address) should be filtered i.e. omitted
   * @return IP address or empty string
   */
  public static String getFrom(HttpServletRequest request, boolean filterPrivateAddresses) {
    String ip = request.getRemoteAddr();

    String headerClientIp = request.getHeader("Client-IP");
    String headerXForwardedFor = request.getHeader("X-Forwarded-For");
    if (StringUtils.isEmpty(ip) && StringUtils.isNotEmpty(headerClientIp)) {
      ip = headerClientIp;
    } else if (StringUtils.isNotEmpty(headerXForwardedFor)) {
      ip = headerXForwardedFor;
    }
    if (filterPrivateAddresses && isPrivateOrLocalAddress(ip)) {
      return StringUtils.EMPTY;
    } else {
      return ip;
    }
  }

  private static boolean isPrivateOrLocalAddress(String address) {
    Matcher regexMatcher = PRIVATE_ADDRESS_PATTERN.matcher(address);
    return regexMatcher.matches();
  }
}

PHP 替代方案

function getIp()
{
    $ip = $_SERVER['REMOTE_ADDR'];

    if (empty($ip) && !empty($_SERVER['HTTP_CLIENT_IP'])) {
        $ip = $_SERVER['HTTP_CLIENT_IP'];
    } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        // omit private IP addresses which a proxy forwarded
        $tmpIp = $_SERVER['HTTP_X_FORWARDED_FOR'];
        $tmpIp = filter_var(
            $tmpIp,
            FILTER_VALIDATE_IP,
            FILTER_FLAG_IPV4 | FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE
        );
        if ($tmpIp != false) {
            $ip = $tmpIp;
        }
    }
    return $ip;
}
于 2016-01-19T10:17:36.683 回答