最近在一个多系统集成的项目中,由于跳转路径含IP地址,每次IP改了重启项目都得改好多地方,甚是麻烦。刚在网上了解到java获取IP地址,给大家分享下:
首先要导入jar包
request.getRemoteAddr(),这种方法在大部分情况下都是有效的。但是在通过了Apache,Squid等反向代理软件就不能获取到客户端的真实IP地址了。
下面是我在网上了解到的方法
方法一:
public String getIpAddr(HttpServletRequest request) { String ip = request.getHeader("x-forwarded-for"); if(ip == null || ip.length() == 0) { ip = request.getRemoteAddr(); } return ip; }
方法二:
public String getIpAddr(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; }
原创文章,作者:Maggie-Hunter,如若转载,请注明出处:https://blog.ytso.com/7498.html