文章目录
前言
因为想记录客户端请求的IP地址,故记录如下所示
一、实现方式
实现方式主要分为以下两步
- 获取HttpServletRequest
直接看代码即可,如下所示:
ServletRequestAttributes attributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
- 获取IP地址(已考虑反向代理的情况)
实现如下所示:
public static String getIpAddr(HttpServletRequest request)
{
if (request == null)
{
return "unknown";
}
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("X-Forwarded-For");
}
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("X-Real-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
{
ip = request.getRemoteAddr();
}
return "0:0:0:0:0:0:0:1".equals(ip) ? "127.0.0.1" : ip;
}
二、总结
都看到这里啦~说明你也和我一样热爱技术、善于发掘问题的根源,不妨给我的博客点个赞8
最后我给我自己的开源项目【简帐】打个广告(后端、前端、小程序三端开源),如果star超过20个我就出一个从零开始的教程
github地址: