Tomcat Servlet request.getRemoteAddr()所得值为0:0:0:0:0:0:0:1

环境:

tomcat5.6

JSP

UTF-8

IP协议:IPv4,IPv6

服务器和访问者在同一机器上。


问题描述

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

[b]原因及解决方案[/b]

因为机器上启用的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文件。

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;
    }

猜你喜欢

转载自feilong8805.iteye.com/blog/1973027
0