如何使用java获取客户端系统ip?

时间:2014-09-18 06:42:31

标签: java jsp servlets

我正在开发Web应用程序,我需要知道谁都访问我的Web应用程序,因为我需要运行我的应用程序的系统的ip(ipv4)地址。我正在使用jsp和servlet可以帮助我修复这个???

我尝试了波纹管代码,但每次用户访问应用程序时都会显示我的IP地址。但我需要客户端ip(ipv4)地址。

try {
                 Enumeration e = NetworkInterface.getNetworkInterfaces();

                 while(e.hasMoreElements()) {
                    NetworkInterface ni = (NetworkInterface) e.nextElement();
                    System.out.println("Net interface: "+ni.getName());

                    Enumeration e2 = ni.getInetAddresses();

                    while (e2.hasMoreElements()){
                       InetAddress ip = (InetAddress) e2.nextElement();
                       System.out.println("IP address: "+ ip.toString());
                    }
                 }
              }
              catch (Exception e) {
                 e.printStackTrace();
              }

4 个答案:

答案 0 :(得分:2)

在HttpServletRequest对象上,您可以使用以下函数来获取远程主机:

request.getRemoteHost()

答案 1 :(得分:1)

Normally, you can use servletRequest.getRemoteAddr() to get the client’s IP address that’s accessing your Java web application.

   String ipAddress = request.getRemoteAddr();

But, if user is behind a proxy server or access your web server through a load balancer (for example, in cloud hosting), the above code will get the IP address of the proxy server or load balancer server, not the original IP address of a client.

 String ipAddress = request.getHeader("X-FORWARDED-FOR");  
   if (ipAddress == null) {  
       ipAddress = request.getRemoteAddr();  
   }

答案 2 :(得分:0)

有几种方法可以做到这一点:

  • 您可以使用HttpServletRequest#getRemoteAddr(),但它会返回与客户端或最后一个代理相对应的IP地址,这可能不是您需要的(如果您真的想要客户端,那就是)
  • 您可以查看一些HTTP标头,例如REMOTE_ADDR,HTTP_X_FORWARDED_FOR(IP列表),HTTP_CLIENT_IP,HTTP_X_FORWARDED,HTTP_X_CLUSTER_CLIENT_IP,HTTP_FORWARDED_FOR和HTTP_FORWARDED。 xxx_forwarded_标头应该为您提供真实的IP地址(而不是代理),但可能为空(例如,某些代理不转发此标头)。

请注意,虽然这些ip很容易被欺骗,但不应该依赖任何关键的(安全性等)

答案 3 :(得分:0)

你也可以这样检查,

public String getRemoteIpAddress(HttpServletRequest req) {      
 String ip = req.getHeader("x-forwarded-for");      
  if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {      
     ip = req.getHeader("Proxy-Client-IP");      
  }      
    if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {      
     ip = req.getHeader("WL-Proxy-Client-IP");      
  }      
  if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {      
      ip = req.getRemoteAddr();      
  }      
  return ip;      
}   

如果用户位于代理服务器后面或通过负载均衡器访问您的Web服务器(例如,在云托管中),上面的代码将获取代理服务器或负载均衡器服务器的IP地址,而不是原始IP地址客户。

要解决此问题,您应该获取请求的HTTP标头“X-Forwarded-For(XFF)”的IP地址。

 //is client behind something?
 String ipAddress = request.getHeader("X-FORWARDED-FOR");  
 if (ipAddress == null) {  
     ipAddress = request.getRemoteAddr();  
 }