通过Request对象获取请求的IP地址

  /**
     * 标识要从哪些消息头中获取IP地址
     */
    private static final String[] getIpArray =
        {"HTTP_X_FORWARDED_FOR", "X-Forwarded-For", "Proxy-Client-IP", "WL-Proxy-Client-IP", "HTTP_CLIENT_IP"};

  /** 
     * 获取请求的IP地址
     * <功能详细描述>
     * @param request
     * @return
     * @see [类、类#方法、类#成员]
     */
    public static String getIP(HttpServletRequest request)
    {
        String ip = "";
        
        for (int i = 0, l = getIpArray.length; i < l; i++)
        
        {
            ip = request.getHeader(getIpArray[i]);
            
            if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip))
            {
                return ip;
            }
            
        }
        
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
        {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

 

posted @ 2017-03-27 11:51  不知名的宋某某  阅读(803)  评论(0编辑  收藏  举报