public static String getIpAddr(HttpServletRequest request) {
String ipAddress = null;
try {
ipAddress = request.getHeader(“x-forwarded-for”);
if (ipAddress == null || ipAddress.length() == 0 || “unknown”.equalsIgnoreCase(ipAddress)) {
ipAddress = request.getHeader(“Proxy-Client-IP”);
}
if (ipAddress == null || ipAddress.length() == 0 || “unknown”.equalsIgnoreCase(ipAddress)) {
ipAddress = request.getHeader(“WL-Proxy-Client-IP”);
}
if (ipAddress == null || ipAddress.length() == 0 || “unknown”.equalsIgnoreCase(ipAddress)) {
ipAddress = request.getRemoteAddr();
if (ipAddress.equals(“127.0.0.1”)) {
// 根据网卡取本机配置的IP
InetAddress inet = null;
try {
inet = InetAddress.getLocalHost();
} catch (UnknownHostException e) {
e.printStackTrace();
}
ipAddress = inet.getHostAddress();
}
}
// 对于通过多个代理的情况,第一个IP为客户端真实IP,多个IP按照’,'分割
if (ipAddress != null && ipAddress.length() > 15) { // “***.***.***.***”.length()
// = 15
if (ipAddress.indexOf(",") > 0) {
ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
}
}
} catch (Exception e) {
ipAddress="";
}
// ipAddress = this.getRequest().getRemoteAddr();
System.out.println(“ip地址================”+ipAddress);
return ipAddress;
}
SpringBoot 获取当前登录用户IP
最新推荐文章于 2024-10-03 22:52:30 发布
该方法主要用于在SpringBoot应用中获取HTTP请求的客户端IP地址。首先尝试从"x-forwarded-for"、"Proxy-Client-IP"、"WL-Proxy-Client-IP"头信息获取,如果都为空或未知,则使用"RemoteAddr"。对于通过多个代理的情况,选择第一个IP。如果所有尝试都失败,返回空字符串。
摘要由CSDN通过智能技术生成