如何在Java中获取客户端IP地址

在Java中,可以使用HttpServletRequest.getRemoteAddr()来获取正在访问Java Web应用程序的客户端的IP地址。

import javax.servlet.http.HttpServletRequest;

String ipAddress = request.getRemoteAddr();

1.代理服务器或Cloudflare

对于位于代理服务器,负载均衡器或流行的Cloudflare解决方案后面的Web应用程序,您应该通过HTTP请求标头X-Forwarded-For(XFF)获得客户端IP地址。

import javax.servlet.http.HttpServletRequest;

	//...
	
	private static String getClientIp(HttpServletRequest request) {

        String remoteAddr = "";

        if (request != null) {
            remoteAddr = request.getHeader("X-FORWARDED-FOR");
            if (remoteAddr == null || "".equals(remoteAddr)) {
                remoteAddr = request.getRemoteAddr();
            }
        }

        return remoteAddr;
    }

2.还没工作吗?

查看客户端的HTTP请求标头,然后尝试确定IP地址的存储位置。

private Map<String, String> getRequestHeadersInMap(HttpServletRequest request) {

        Map<String, String> result = new HashMap<>();

        Enumeration headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String key = (String) headerNames.nextElement();
            String value = request.getHeader(key);
            result.put(key, value);
        }

        return result;
    }

Cloudflare之后的Web应用程序的示例请求标头。

"referer" :"https://www.google.com/",
    "cf-ipcountry" :"US",
    "cf-ray" :"348c7acba8a02210-EWR",
    "x-forwarded-proto" :"https",
    "accept-language" :"en-US,en;q=0.8",
    "cookie" :"__cfduid=d3c6e5d73aa55b6b42fad9600c94849851490726068; _ga=GA1.2.450731937.1490726069",

    "x-forwarded-for" :"100.8.204.40",             // <------ This is client real IP

    "accept" :"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",

    "x-real-ip" :"108.162.219.236",             // <------ This is cloudflare IP

    "x-forwarded-server" :"hostingcompass.com",
    "x-forwarded-host" :"hostingcompass.com",
     "cf-visitor" :"{\"scheme\":\"https\"}",
    "host" :"127.0.0.1:8080",
    "upgrade-insecure-requests" :"1",
    "connection" :"close",
    "cf-connecting-ip" :"100.8.204.40",
    "accept-encoding" :"gzip",
    "user-agent" : "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36"

注意
通常,在您无法在整个请求中找到客户端IP的情况下,Web /代理服务器将请求转发到Java应用服务器之前,它将以标准标头名称(例如x-forwarded-for存储真实的客户端IP请求。标头,请尝试与服务器管理员讨论。

参考文献

  1. Wiki X转发
  2. ServletRequest Java文档
  3. HttpServletRequest JavaDoc
  4. 如何使用Java获取服务器IP地址

标签:
IP地址
java
请求标头

翻译自: https://mkyong.com/java/how-to-get-client-ip-address-in-java/

    原文作者:cyan20115
    原文地址: https://blog.csdn.net/cyan20115/article/details/106551360
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞