Get IP address of client in JSP

2020-06-16 06:01发布

I need to get the IP address of the client in the JSP page. I have tried the following ways:

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")

However, none of those ways did return the desired IP address. How do I get the IP address of the client in the JSP page?

标签: java jsp ip
4条回答
手持菜刀,她持情操
2楼-- · 2020-06-16 06:08

Is your application server behind a load balancer, a proxy or a web server? Just an example; F5 load balancer exposes the client IP address with the "rlnclientipaddr" header:

request.getHeader("rlnclientipaddr");
查看更多
狗以群分
3楼-- · 2020-06-16 06:08

do you use reverse proxy like apache proxy? http://httpd.apache.org/docs/2.2/mod/mod_proxy.html

When acting in a reverse-proxy mode (using the ProxyPass directive, for example), mod_proxy_http adds several request headers in order to pass information to the origin server. These headers are:

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.
查看更多
劫难
4楼-- · 2020-06-16 06:14

To get IP address of the client, I've used the following method

<%   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();  
        }
        %>

Hope this helps, please leave a feed back.

查看更多
等我变得足够好
5楼-- · 2020-06-16 06:23
<%
out.print( request.getRemoteAddr() );
out.print( request.getRemoteHost() );
%>

You may not get the real client IP if a the client is behind a proxy, you will get the IP of the proxy and not the client. However, the proxy may include the requesting client IP in a special HTTP header.

<%
out.print( request.getHeader("x-forwarded-for") );
%>
查看更多
登录 后发表回答