在jsp页面中,可以使用
把这句话,放到网页中,即可获取真实的公网IP地址。
request.getRemoteAddr();
来获取最简单的IP地址,但是在公网中,这样获取IP地址就会出现问题,因为request.getRemoteAddr()获得的是网卡的ip地址。
但是,现在越来越多的人家里开始使用无线路由器之类的对网络进行NAT转换的网络设备,所以,这样获取出来的ip地址只会是192.168.0.2之类的IP地址,无法实现我们的需求。提供两种解决方案:
有非常多的ip查询api可以调用,例如www.ip138.com/ip2city.asp,http://ip.blueera.net/api?action=show
<iframe src="http://www.ip138.com/ip2city.asp" frameborder="0" scrolling="no" width="100%" height="100%"></iframe>
把这句话,放到网页中,即可获取真实的公网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;
}