C# IP地址访问控制

            string ipLimit = "192.168.152.x,192.168.153.x,192.168.154.x,192.168.155.x,192.168.156.x,192.168.157.x,192.168.158.x,192.168.159.x,192.168.x.x";

            string[] arrSeperators = { "," };

            string[] ipList = ipLimit.Split(arrSeperators, StringSplitOptions.RemoveEmptyEntries);

            if (!CheckIPLimit(ipList, GetRemoteIP()))
            {
                   return“不可以访问”;
            }

获得请求的IP地址函数GetRemoteIP():

        private string GetRemoteIP()
        {
            string ip = "";

            if (Context.Request.ServerVariables["HTTP_VIA"] != null) // 服务器, using proxy
            {
                //得到真实的客户端地址
                ip = Context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString(); // Return real client IP.
            }
            else//如果没有使用代理服务器或者得不到客户端的ip not using proxy or can't get the Client IP
            {
                // 得到服务端的地址
                ip = Context.Request.ServerVariables["REMOTE_ADDR"].ToString(); //While it can't get the Client IP, it will return proxy IP.
            }

            return ip;
        }
    }
下面的函数将string[] ipList与请求IP一一比较(分段比较):

   private bool CheckIPLimit(string[] ipList, string remoteIP)
        {
            foreach (string ip in ipList)
            {
                if (CompareIP(ip, remoteIP))
                {
                    return true;
                }
            }
            return false;
        }

        private bool CompareIP(string oldIP, string newIP)
        {
            string[] arrSeperators = { "." };

            string[] oldIPList = oldIP.Split(arrSeperators, StringSplitOptions.RemoveEmptyEntries);

            string[] newIPList = newIP.Split(arrSeperators, StringSplitOptions.RemoveEmptyEntries);

            if (oldIPList.Length != newIPList.Length)
            {
                return false;
            }

            for (int i = 0; i < oldIPList.Length; i++)
            {
                if (oldIPList[i] != checkedIP & oldIPList[i] != newIPList[i])//截取的ip是‘x’则是true
                {
                    return false;
                }
            }

            return true;
        }





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值