Java后台获取当前访问客户端的真实IP地址(外网或内网地址)

JSP页面获取客户的IP地址方法

request.getRemoteAddr()

Java后台获取客户的IP地址方法(后台指java/class文件中。再如果域名访问使用了反向代理软件的,上面的方法获取的是内网地址,下面获取的才是客户的外网ip)

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

上面获取的可能有多个ip逗号分隔的情况,即wifi的ip和手机卡运营商的ip,例如:210.22.98.30, 122.190.2.78;如果只想获取一个,此时应该采用下面这种方法

public static 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(); 
	} 
	if(ip != null) {
		ip=ip.split(",")[0];
	}
	return ip; 
}
正在加载评论...