C# IP地址存取控制

來源:互聯網
上載者:User
            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//如果沒有使用Proxy 伺服器或者得不到用戶端的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;        }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.