7

我需要在 JSP 页面中获取客户端的 IP 地址。我尝试了以下方法:

request.getRemoteAddr()
request.getHeader("X_FORWARDED_FOR")
request.getHeader("HTTP_CLIENT_IP")
request.getHeader("WL-Proxy-Client-IP")
request.getHeader("Proxy-Client-IP")
request.getHeader("REMOTE_ADDR")

但是,这些方法都没有返回所需的 IP 地址。如何在 JSP 页面中获取客户端的 IP 地址?

4

4 回答 4

13

要获取客户端的 IP 地址,我使用了以下方法

<%   String ip = request.getHeader("X-Forwarded-For");  
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
            ip = request.getHeader("Proxy-Client-IP");  
        }  
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
            ip = request.getHeader("WL-Proxy-Client-IP");  
        }  
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
            ip = request.getHeader("HTTP_CLIENT_IP");  
        }  
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");  
        }  
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
            ip = request.getRemoteAddr();  
        }
        %>

希望这有帮助,请留下反馈。

于 2014-03-19T10:32:45.477 回答
6
<%
out.print( request.getRemoteAddr() );
out.print( request.getRemoteHost() );
%>

如果客户端在代理后面,您可能无法获得真实的客户端 IP,您将获得代理的 IP 而不是客户端。但是,代理可能会在特殊的 HTTP 标头中包含请求客户端 IP。

<%
out.print( request.getHeader("x-forwarded-for") );
%>
于 2012-07-27T07:41:59.623 回答
3

您的应用程序服务器是在负载平衡器、代理还是 Web 服务器后面?只是一个例子;F5 负载均衡器使用“rlnclientipaddr”标头公开客户端 IP 地址:

request.getHeader("rlnclientipaddr");
于 2012-07-27T07:49:38.307 回答
0

你使用像apache代理这样的反向代理吗? http://httpd.apache.org/docs/2.2/mod/mod_proxy.html

在反向代理模式下(例如,使用 ProxyPass 指令),mod_proxy_http 添加几个请求标头以便将信息传递给源服务器。这些标题是:

X-Forwarded-For
The IP address of the client.
X-Forwarded-Host
The original host requested by the client in the Host HTTP request header.
X-Forwarded-Server
The hostname of the proxy server.
于 2012-07-27T07:36:25.720 回答