根绝ip限制访问

       今天有个客户要求在内网里限制下访问,根据ip端,自己就粗略写了一些,方法比较笨,不过很实用,代码如下:

 

    //限制ip段访问
    public static bool CheckIp()
    {
        bool fig = false;

        //首先获得客户端ip
        string clientIp = GetIP();

        if (clientIp.Substring(0, clientIp.LastIndexOf(".")) == "10.57.70")
        {
            //判断最后一位数字的范围
            int lastNum = Convert.ToInt32(clientIp.Substring(clientIp.LastIndexOf(".") + 1));
            if (lastNum <= 255 && lastNum > 0)
            {
                fig = true;
            }
        }
        else if (clientIp.Substring(0, clientIp.LastIndexOf(".")) == "10.57.74")
        {
            int lastNum = Convert.ToInt32(clientIp.Substring(clientIp.LastIndexOf(".") + 1));
            if (lastNum <= 191 && lastNum >= 0)
            {
                fig = true;
            }
        }
        else if (clientIp.Substring(0, clientIp.LastIndexOf(".")) == "10.57.75")
        {
            int lastNum = Convert.ToInt32(clientIp.Substring(clientIp.LastIndexOf(".") + 1));
            if (lastNum <= 63 && lastNum >= 0)
            {
                fig = true;
            }
        }
        else if (clientIp.Substring(0, clientIp.LastIndexOf(".")) == "10.57.76")
        {
            int lastNum = Convert.ToInt32(clientIp.Substring(clientIp.LastIndexOf(".") + 1));
            if (lastNum <= 63 && lastNum >= 0)
            {
                fig = true;
            }
        }
        else if (clientIp.Substring(0, clientIp.LastIndexOf(".")) == "10.57.74")
        {
            int lastNum = Convert.ToInt32(clientIp.Substring(clientIp.LastIndexOf(".") + 1));
            if (lastNum <= 191 && lastNum >= 128)
            {
                fig = true;
            }
        }
        return fig;


    }
    public static string GetIP()
    {
        // 优先取得代理IP
        string userHostAddress = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
        if (string.IsNullOrEmpty(userHostAddress))
        {
            //没有代理IP则直接取客户端IP
            userHostAddress = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
        }
        if ((userHostAddress != null) && !(userHostAddress == string.Empty))
        {
            return userHostAddress;
        }
        return "0.0.0.0";
    }

 然后在限制的页面里调用这段代码即可,呵呵,时间关系,没考虑太多,大家可以在简便一些,思路大概就是这样!

posted @ 2012-04-16 09:37  双魂人生  阅读(535)  评论(1编辑  收藏  举报