Mennan
Mennan

Reputation: 4497

How to create ip mask and filter it on .net?

i defined some rules and it includes ip adresses like this.

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 means "all". I get user ip on page_load and I want to compare it to my rules. How do I compare user ip and rules in ip list?

For example if ip starts "10" not block it...also if ip ends "10" block it like that...

(also, sorry about my English)

Upvotes: 3

Views: 2392

Answers (1)

Dmitry Samuylov
Dmitry Samuylov

Reputation: 1564

Here's one way you can accomplish what you seem to be describing:

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

NOTE: The code above will set the Authorization flag to the last rule in the list that it matched. If multiple rules match, only the last match will be kept and previous ones are ignored. Keep this in mind when defining the rules and think about the order of your rules in the dictionary.

Also you can definitely move the Rule regular expression strings out into a config file if you want and read them in from there. I'll leave that part to you.

Upvotes: 1

Related Questions