c# - 如何创建 ip 掩码并在 .net 上对其进行过滤?

标签 c# asp.net ip

我定义了一些规则,它包括像这样的 ip 地址。

ip adress : 192.168.2.10 , block:true |
ip adress : 192.168.3.x , block:true |
ip adress : 10.x.x.x , block:false 

x 表示“全部”。我在 page_load 上获得了用户 ip,我想将它与我的规则进行比较。如何比较用户 ip 和 ip 列表中的规则?

例如,如果 ip 以“10”开头,则不阻止它……如果 ip 以“10”结尾,则这样阻止它……

(另外,对不起我的英语)

最佳答案

这里有一种方法可以完成您所描述的内容:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text.RegularExpressions;

namespace WebApplication1
{
    public partial class _Default : System.Web.UI.Page
    {
        private Dictionary<string, bool> rules = null;
        public Dictionary<string, bool> Rules
        {
            get
            {
                if (rules == null)
                {
                    // 1. use [0-9]{1,3} instead of x to represent any 1-3 digit numeric value
                    // 2. escape dots like such \. 
                    rules = new Dictionary<string, bool>();
                    rules.Add(@"192\.168\.2\.10", true);
                    rules.Add(@"192\.168\.3\.[0-9]{1,3}", true);
                    rules.Add(@"10\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}", false);
                }
                return rules;
            }
        }

        protected bool IsAuthorizedByIP()
        {
            bool isAuthorized = false;

            // get current IP
            string currentIP = Request.ServerVariables["REMOTE_ADDR"];
            currentIP = "10.168.2.10";

            // set Authorization flag by evaluating rules
            foreach (var rule in Rules)
            {
                if (Regex.IsMatch(currentIP, rule.Key))
                    isAuthorized = rule.Value;
            }

            return isAuthorized;
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (IsAuthorizedByIP())
            {
                // do something that applies to authorized IPs
                Response.Write("You are authorized!");
            }
        }
    }
}

注意:上面的代码会将授权标志设置为它匹配的列表中的最后一条规则。如果多个规则匹配,则只保留最后一个匹配项,忽略之前的匹配项。在定义规则时请牢记这一点,并考虑您的规则在字典中的顺序。

此外,如果需要,您绝对可以将规则正则表达式字符串移出到配置文件中,然后从那里读取它们。我会把那部分留给你。

关于c# - 如何创建 ip 掩码并在 .net 上对其进行过滤?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9669957/

相关文章:

javascript - 如何在 JavaScript 中将十六进制(缓冲区)转换为 IPv6

macOS NKE ipf_filter – IP 校验和为 0

java - 在 Java 中比较 Ip 范围列表(与 CIDR)

c# - EFCore 保存具有关系 ID 的实体

c# - NamedPipeServerStream 和 WaitForConnection 方法

c# - ASP.Net httpwebrequest 不发布请求正文

asp.net - IIS 中的服务引用

c# - 两个包含接口(interface)的列表与一个包含具有两个接口(interface)的结构的列表

c# - 为什么我从 Web API Controller 上的 Post 方法得到一个空值?

javascript - jQuery 可选导致 ASP.NET Ajax 应用程序中的完整回发