1

我正在尝试public通过 servlet 获取客户端 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);

但这只能返回 localhost IP,如下面的输出所示:

1. ip: null
2. ip: null
3. ip: null
4. ip: null
4. ip: 127.0.0.1

有什么帮助吗?

4

2 回答 2

2

它取决于代理服务器/负载平衡器及其配置。在大多数情况下,可以通过以下方式获取 IP

request.getHeader("x-forwarded-for") 

或者

request.getHeader("x-real-ip")

如果在您的服务器之前您有代理服务器,请确保代理将标头传递给您的服务器,例如在 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;
    ...
  }
于 2013-09-02T10:34:34.470 回答
0

我喜欢这个,你可以试试

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;      
} 
于 2013-11-06T07:00:27.360 回答