C# .Net 判斷IP地址是否符合某IP段技巧

在YuebonCore快速開發框架開源項目中涉及到當前登錄用戶登錄IP是否被禁止登錄訪問系統,獲取登錄IP後怎麼去判斷過濾呢?我們採用將IP地址轉爲Int32數字型,然後去判斷大小。

 

Sql sever IP地址轉int型

cast(replace(StartIP,'.','') as bigint)

獲取當前用戶IP地址字符串轉int型

int ipv = ip.Replace(".", "").ToInt();

  

綜合起來方法如下:

        /// <summary>
        /// 驗證IP地址是否被拒絕
        /// </summary>
        /// <param name="ip"></param>
        /// <returns></returns>
        public bool ValidateIP(string ip)
        {
            long ipv = ip.Replace(".", "").ToLong();
            string where = " (cast(replace(StartIP,'.','') as bigint)>=" + ipv + " and cast(replace(EndIP,'.','') as bigint)<=" + ipv + ") and FilterType=0 and EnabledMark=1";
            int count = GetCountByWhere(where);
            return count > 0 ? true : false;
        }

  

號外:

YuebonCore是基於.NetCore3.1開發的權限管理及快速開發框架

開源地址:https://gitee.com/yuebon/YuebonNetCore

官方文檔:http://docs.v.yuebon.com

 

大家對此問題有什麼好的方法呢?評論區討論。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章