[英]Servlet - get client public IP
I'm trying to get client public
ip address via servlet as below: 我正在尝试通过servlet获取客户端public
IP地址,如下所示:
String ip = request.getHeader("X-Forwarded-For");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
System.out.println("1. ip: "+ip);
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
System.out.println("2. ip: "+ip);
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_CLIENT_IP");
}
System.out.println("3. ip: "+ip);
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_X_FORWARDED_FOR");
}
System.out.println("4. ip: "+ip);
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
System.out.println("4. ip: "+ip);
but this only able to return the localhost IP, as you see in below output: 但这只能返回本地主机IP,如下面的输出所示:
1. ip: null
2. ip: null
3. ip: null
4. ip: null
4. ip: 127.0.0.1
Any help? 有什么帮助吗?
It depends from proxy server/load balancer and their configurations. 它取决于代理服务器/负载平衡器及其配置。 In most cases it is possible to get IP by 在大多数情况下,可以通过以下方式获取IP:
request.getHeader("x-forwarded-for")
or 要么
request.getHeader("x-real-ip")
In case when before your server you have proxy server, make sure that proxy pass headers to your server, eg in case of nginx it should look like 如果在服务器之前有代理服务器,请确保代理将标头传递给您的服务器,例如,在nginx的情况下,它应该看起来像
server {
server_name domain.com;
...
location /path-to-server {
...
proxy_pass localhost:8080;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
...
}
I do like this,you can have a try 我喜欢这样,你可以试试看
public String getIpAddr(HttpServletRequest request) {
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.getRemoteAddr();
}
return ip;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.