【问题标题】:How to create ip mask and filter it on .net?如何创建 ip 掩码并在 .net 上对其进行过滤?
【发布时间】:2012-03-29 00:33:09
【问题描述】:

我定义了一些规则,它包括这样的 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”结尾,则像那样阻止它...

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

【问题讨论】:

  • 哎呀...已经有可供您选择的选项。 Here's 一个。如果您坚持自己做,您可能想了解一下 IP 地址标准。它们可以让你的工作变得更简单(首先想到的是 CIDR 表示法)。
  • @M.Babcock:我认为您链接的示例只是使用单个 IP 地址而不是阻止,因此如果您想阻止 192.168.0.0/16 或其他内容,将会很笨拙......
  • 虽然它不是完全重复的 stackoverflow.com/questions/1499269/… 应该给你足够的信息来做你想做的事......主要区别只是学习他们使用的不同符号。
  • @Chris - 你是对的,但这仍然比创造一种新的方式来表示 IP 掩码要好。
  • 我很抱歉重复的帖子和谢谢你的 cmets

标签: c# asp.net ip


【解决方案1】:

您可以通过以下方式完成您所描述的内容:

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!");
            }
        }
    }
}

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

如果你愿意,你也可以将规则正则表达式字符串移到一个配置文件中,然后从那里读入。我会把这部分留给你。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-12-11
    • 1970-01-01
    • 1970-01-01
    • 2017-06-14
    • 1970-01-01
    • 2021-06-24
    • 1970-01-01
    • 2022-01-02
    相关资源
    最近更新 更多