H5W3
当前位置:H5W3 > 其他技术问题 > 正文

java获取手机客户端的ip地址?

在客户端和服务之间增加了中间转发服务器,所以获取到都是转发服务器的地址,尝试了网上帖子的方法后还是不行。。。求大神帮忙!

public static String GetIP(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;
}

回答:

你说了,有转发服务器,首先要保证转发时要设置原始访问ip,才能保证后面可以获取到。比如nginx转发的可以配置:

proxy_set_header  Host               $host;  
      proxy_set_header  X-Real-IP          $remote_addr;#提交请求的真实ip,为了目标服务也能获取到请求的真实ip  
      proxy_set_header  X-Forwarded-For    $proxy_add_x_forwarded_for;  
      proxy_set_header  X-Forwarded-Proto  http;  

本文地址:H5W3 » java获取手机客户端的ip地址?

评论 0

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址