获取客户端真实ip
// Request 该接口是blade包下的,不同框架使用不同的接口即可。一般spring boot的可以使用java封装的httpServletRequest 对应获取头信息改为get方式即可。
public String getIpAddr(Request request) throws UnknownHostException {
String Xip = request.header("X-Real-ip");
String XFor = request.header("X-Forwarded-For");
if (StringUtils.isNotBlank(Xip) && !"unKnown".equalsIgnoreCase(XFor)) {
//多次反向代理后会有多个ip值,第一个ip才是真实ip
int index = XFor.indexOf(",");
if (index != -1) {
return XFor.substring(0, index);
} else {
return XFor;
}
}
XFor = Xip;
if (StringUtils.isNotBlank(XFor)&& !"unKnown".equalsIgnoreCase(XFor)) {
return XFor;
}
if (StringUtils.isBlank(XFor) || "unknown".equalsIgnoreCase(XFor)) {
XFor = request.header("Proxy-Client-IP");
}
if (StringUtils.isBlank(XFor) || "unknown".equalsIgnoreCase(XFor)) {
XFor = request.header("WL-Proxy-Client-IP");
}
if (StringUtils.isBlank(XFor) || "unknown".equalsIgnoreCase(XFor)) {
XFor = request.header("HTTP_CLIENT_IP");
}
if (StringUtils.isBlank(XFor) || "unknown".equalsIgnoreCase(XFor)) {
XFor = request.header("HTTP_X_FORWARDED_FOR");
}
if (StringUtils.isBlank(XFor) || "unknown".equalsIgnoreCase(XFor)) {
XFor = InetAddress.getLocalHost().getHostAddress();
}
return XFor;
}
获取客户端信息
相关引用包
<dependency>
<groupId>eu.bitwalker</groupId>
<artifactId>UserAgentUtils</artifactId>
<version>1.20</version>
</dependency>
UserAgent userAgent = UserAgent.parseUserAgentString(request.header("User-Agent")); //req就是request请求
Browser browser = userAgent.getBrowser(); //获取浏览器信息
OperatingSystem os = userAgent.getOperatingSystem(); //获取操作系统信息
StringBuffer userInfo = new StringBuffer();
userInfo.append("操作系统:" + os.toString() + " \r\n 浏览器:" + browser.toString()).append(" \r\n HOST:" + request.header("Host"));