最近在一个多系统集成的项目中,由于跳转路径含IP地址,每次IP改了重启项目都得改好多地方,甚是麻烦。刚在网上了解到java获取IP地址,给大家分享下:

首先要导入jar包

Java ip 地址 比对 java查询ip地址_IP

request.getRemoteAddr(),这种方法在大部分情况下都是有效的。但是在通过了Apache,Squid等反向代理软件就不能获取到客户端的真实IP地址了。 

下面是我在网上了解到的方法

方法一:

1 public String getIpAddr(HttpServletRequest request) { 
2         String ip = request.getHeader("x-forwarded-for"); 
3         if(ip == null || ip.length() == 0) { 
4             ip = request.getRemoteAddr(); 
5         } 
6         return ip; 
7     }

方法二:

1 public String getIpAddr(HttpServletRequest request) { 
 2         String ip = request.getHeader("x-forwarded-for"); 
 3         if(ip == null || ip.length() == 0||"unknown".equalsIgnoreCase(ip)) { 
 4             ip = request.getHeader("Proxy-Client_IP"); 
 5         } 
 6         if(ip == null || ip.length() == 0||"unknown".equalsIgnoreCase(ip)) { 
 7             ip = request.getHeader("WL-Proxy-Client_IP"); 
 8         } 
 9         if(ip == null || ip.length() == 0||"unknown".equalsIgnoreCase(ip)) { 
10             ip = request.getRemoteAddr(); 
11         } 
12         return ip; 
13     }