2012-03-12 4 views
3

몇 가지 규칙을 정의했으며 이와 같은 IP 주소를 포함합니다.IP 마스크를 만들고 .net에서 필터링하는 방법은 무엇입니까?

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는 "all"을 의미합니다. page_load에서 사용자 ip를 얻었고이를 내 규칙과 비교하고 싶습니다. IP 목록에서 사용자 ip와 규칙을 비교하려면 어떻게합니까? 예를 들어

는 IP는 IP 그런 "10"블록을 종료 또한 경우에 ... "10"을 막지 시작하면 ...

(미안도를, 제 영어 실력에 대해)

+0

Yikes ... 이미 사용 가능한 옵션이 있습니다. [Here 's] (http://www.hanselman.com/blog/AnIPAddressBlockingHttpModuleForASPNETIn9Minutes.aspx)가 있습니다. IP 주소 표준에 대해 조금 배우고 싶을 수도 있습니다. 그들은 당신의 직업을 훨씬 단순하게 만들 수 있습니다. (처음 생각할 때 CIDR 표기법이라고 생각합니다.) –

+0

@ M.Babcock : 당신이 연결된 예제가 블록이 아니라 개별 IP 주소를 사용하고 있기 때문에 192.168.0.0/16 또는 뭔가를 차단하려는 경우 다루기 힘들어 질 것이라고 생각합니다. – Chris

+0

매우 중복되지는 않지만 http : /stackoverflow.com/questions/1499269/how-to-check-if-an-ip-address-is-within-a-particular-subnet이 원하는 정보를 제공해야합니다 ... 주요 차이점은 그들이 사용하는 다른 표기법을 배우는데 – Chris

답변

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

참고 : 위의 코드가 일치하는 목록의 마지막 규칙에 권한 부여 플래그를 설정합니다. 여러 규칙이 일치하면 마지막 일치 항목 만 유지되고 이전 규칙은 무시됩니다. 규칙을 정의 할 때 사전에 규칙의 순서를 생각할 때이를 명심하십시오.

또한 원하는 경우 규칙 정규 표현식 문자열을 구성 파일로 이동하여 거기에서 읽을 수 있습니다. 나는 그 부분을 너에게 맡길 것이다.

관련 문제