域名注册网站系统seo技术交流
因为项目功能的需求获取访问端的ip地址。
需要关注两点
1. 获取 HttpServletRequest 对象,该对象中包含了客户端请求的相关信息
2. 从HttpServletRequest 对象中获取到需要的ip地址
对于第一点,我们可以直接使用spring框架的强项,依赖注入,使用注释直接注入。
@Autowired
private HttpServletRequest request;
对于第二点,网上已经有厉害的人实现了,代码参考根据HttpServletRequest 对象获取IP地址。
/** * @Description: 获取客户端IP地址 */ private String getIpAddr(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.getRemoteAddr(); if(ip.equals("127.0.0.1")){ //根据网卡取本机配置的IP InetAddress inet=null; try { inet = InetAddress.getLocalHost(); } catch (Exception e) { e.printStackTrace(); } ip= inet.getHostAddress(); } } // 多个代理的情况,第一个IP为客户端真实IP,多个IP按照','分割 if(ip != null && ip.length() > 15){ if(ip.indexOf(",")>0){ ip = ip.substring(0,ip.indexOf(",")); } } return ip;
}
版权声明:本文为CSDN博主「kioo」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/kioo_i_see/article/details/71630014