HttpServletRequest如何获取真实IP地址呢?

java-教程王 Servlet 发布时间:2022-01-01 21:21:35 阅读数:2608 1
下文笔者讲述使用HttpServletRequest获取真实IP(无代理)的方法分享,如下所示:
实现思路:
    使用request.getHeader("x-forwarded-for")获取头文件的方式获取IP地址
例:
  
//方式1:获取实际IP
public String getRemortIP(HttpServletRequest request) {
  if (request.getHeader("x-forwarded-for") == null) {
   return request.getRemoteAddr();
  }
  return request.getHeader("x-forwarded-for");
}
//方式2:获取实际IP
public String getRemoteHost(javax.servlet.http.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.equals("0:0:0:0:0:0:0:1")?"127.0.0.1":ip;
}
版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。

本文链接: https://www.Java265.com/Servlet/202201/240.html

最近发表

热门文章

好文推荐

Java265.com

https://www.java265.com

站长统计|粤ICP备14097017号-3

Powered By Java265.com信息维护小组

使用手机扫描二维码

关注我们看更多资讯

java爱好者