Spring框架获取请求ip小示例

https://blog.csdn.net/kioo_i_see/article/details/71630014

因为项目功能的需求获取访问端的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;   
    }  

接下来就可以使用获取到的ip了

猜你喜欢

转载自blog.csdn.net/jiulanhao/article/details/81166593
今日推荐