Tomcat下使用Servlet的request.getRemoteAddr()所得ip值为0:0:0:0:0:0:0:1的问题

环境
win7 x64
tomcat5.6
JSP
UTF-8
IP协议:IPv4,IPv6
服务器和访问者在同一机器上。

问题描述
上传文件时,为了避免文件名重复,打算利用IP地址+时间戳的方式和给文件命名。但是,从本机上访问本机服务器时,利用request.getRemoteAddr()函数获取IP地址,得到的是0:0:0:0:0:0:0:1。因为是按IPv4的方式和解析的,所以使得保存文件失败。

解决方案
因为机器上启用的IPv6协议,所以在对localhost进DNS解析时,得到的是IPv6形式的本机地址0:0:0:0:0:0:0:1。因此在利用http://localhost:8080/demo/ 访问时,request.getRemoteAddr()函数才会得到上面的结果。
可以修改hosts文件。位置:C:\Windows\System32\drivers\etc。添加上一句127.0.0.1       localhost,这样request.getRemoteAddr()函数得到的将是127.0.0.1。
此外,利用别的机器来访问本机服务器,则不会出现上述上问题,能够取得它的IPv4地址。对于网上所说的因为tomcat的反向代理,使得request.getRemoteAddr()无法获得客户端真实IP的问题,我目前还不是很理解。

关于hosts文件
hosts文件相当于一个位于本地的IP地址到域名的映射文件,可以提供DNS解析。如果想访问的网站被域名污染(域名劫持),可以预先将IP,域名对写入hosts文件。

source:
public static String getAddressIP(HttpServletRequest request) {
      String ipAddress = null;
      ipAddress = request.getHeader("x-forwarded-for");
      if (ipAddress == null || ipAddress.length() == 0
          || "unknown".equalsIgnoreCase(ipAddress)) {
        ipAddress = request.getHeader("Proxy-Client-IP");
      }
      if (ipAddress == null || ipAddress.length() == 0
          || "unknown".equalsIgnoreCase(ipAddress)) {
        ipAddress = request.getHeader("WL-Proxy-Client-IP");
      }
      if (ipAddress == null || ipAddress.length() == 0
          || "unknown".equalsIgnoreCase(ipAddress)) {
        ipAddress = request.getRemoteAddr();
        if (ipAddress.equals("127.0.0.1")) {
          // Based on the IP network card in the machine configuration
          InetAddress inet = null;
          try {
            inet = InetAddress.getLocalHost();
          } catch (UnknownHostException e) {
            e.printStackTrace();
          }
          ipAddress = inet.getHostAddress();
        }
      
      }
      
      // In the case of through multiple agents, 
      // the first real IP IP for the client, 
      // multiple IP in accordance with the ', 'segmentation
      if (ipAddress != null && ipAddress.length() > 15) { // "***.***.***.***".length()
                                                          // = 15
        if (ipAddress.indexOf(",") > 0) {
          ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
        }
      }
      
      return ipAddress;
    }


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值