如何从Java中的HTTP标头中检索IP地址

2022-09-03 08:49:32

我很好奇是否有任何图书馆已经处理过这类事情,或者我必须再次自己做。所以,问题是我想从服务器上的访问者HTTP标头请求中获取IP地址字段,并在Java中完成整个过程?任何帮助都会很好。提前致谢。


答案 1

使用 javax.servlet.http.HttpServletRequest 对象的 getHeader(String Name) 方法来检索变量的值。下面是示例代码:Remote_Addr

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

如果此代码返回空字符串,则按以下方式使用:

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

if (ipAddress == null) {
    ipAddress = request.getRemoteAddr();
}

答案 2

尽管有一个被接受的答案已经被高度支持,但我想提出一个替代方案,并指出被接受的答案的缺点。

request.getHeader("Remote_Addr")指定为返回与 完全相同的 。因此,同时检查两者是没有意义的。另请注意,这是 一种方法(即 HTTP 不可知论者),而 在 中。request.getRemoteAddr()getRemoteAddrjavax.servlet.ServletRequestgetHeaderjavax.servlet.http.HttpServletRequest

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

我不知道使用over有多可靠。在Java中,我宁愿使用直接的缩写形式。有关讨论,请参阅 https://stackoverflow.com/a/3834169/131929。大写/小写没有区别,因为在敏感指定为大小写。HTTP_X_FORWARDED_FORX-Forwarded-ForgetHeader

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

推荐