标签:text header java commons set sas contex ble _for
从今年7月24号,没有玩游戏到现在不知不觉(还是一个来月啊,这记性啊,我还以为过了老长时间了呢!)。真的像那个相对论中所说的那样啊,冬天的火堆,夏天的火炉,同样的时间,在第四维度是不一样的世界。好了,笔者利用15分钟的时间,探究一下怎么获取服务器访问者的IP地址。 /**
* 获取当前访问者IP地址
* @param request 请求
* @return IP地址
*/
public static String getVisitIp(HttpServletRequest request) {
/**
* 在一般情况下使用Request.getRemoteAddr()即可,
* 但是经过nginx等反向代理软件后,这个方法会失效。
* 本方法先从Header中获取X-Real-IP,
* 如果不存在再从X-Forwarded-For获得第一个IP(用,分割),
* 如果还不存在则调用Request .getRemoteAddr()
*/
String ip = request.getHeader("X-Real-IP");
/**org.apache.commons.lang.StringUtils处理字符串类
* IsEmpty/IsBlank – 检查字符串是否有内容。
* IsAlpha/IsNumeric/IsWhitespace/IsAsciiPrintable – 判断字符是否在字符串中。
*/
if (!StringUtils.isBlank(ip) && !"unknown".equalsIgnoreCase(ip)) {
return ip;
}
ip = request.getHeader("X-Forwarded-For");
if (!StringUtils.isBlank(ip) && !"unknown".equalsIgnoreCase(ip)) {
// 多次反向代理后会有多个IP值,第一个为真实IP。
int index = ip.indexOf(‘,‘);
if (index != -1) {
return ip.substring(0, index);
} else {
return ip;
}
} else {
return request.getRemoteAddr();
}
}
调用:
HttpServletRequest request = ServletActionContext.getRequest();
String IP = AllServiceIsHere.getVisitIp(request);
System.err.println(IP);
走你:
public static String getIp(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.getHeader("HTTP_CLIENT_IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_X_FORWARDED_FOR");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
return ip;
}
**同样调用:**
HttpServletRequest request = ServletActionContext.getRequest();
String IP = AllServiceIsHere.getIp(request);
System.err.println(IP);
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script type="text/javascript" src="js/jquery.js" ></script>
</head>
<body>
<div id="20180911"></div>
</body>
<script language=javascript>
var wshNetwork = new ActiveXObject("WScript.Network");
$("#20180911").html("域名 = "+ wshNetwork.UserDomain+"<br/>"
啊,还是走后台吧。省心!
标签:text header java commons set sas contex ble _for
原文地址:http://blog.51cto.com/13479739/2174036