根据请求的HttpServletRequest获取ip地址工具类
2021-03-05 03:27
标签:turn 通过 ipad length 获取 tac 调用 let string 在开发中总会根据用户请求的HttpServletRequest去获取用户ip 所以封装了一个工具类 可以减少重复性操作 上代码 工具类 package com.cm.weixin.pay.utils; import java.net.InetAddress; import javax.servlet.http.HttpServletRequest; public class IpUtils { 测试调用 根据请求的HttpServletRequest获取ip地址工具类 标签:turn 通过 ipad length 获取 tac 调用 let string 原文地址:https://www.cnblogs.com/java-cxh/p/12910664.html
import java.net.UnknownHostException;
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="";
}
return ipAddress;
}
}String ip = IpUtils.getIpAddr(request);
可以成功获取用户的ip作为记录日志或者其他地方使用
文章标题:根据请求的HttpServletRequest获取ip地址工具类
文章链接:http://soscw.com/index.php/essay/60261.html