여기에 하나의 당신은 당신이 무엇을 보인다 달성 할 수있는 방법을 설명합니다 :
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!");
}
}
}
}
참고 : 위의 코드가 일치하는 목록의 마지막 규칙에 권한 부여 플래그를 설정합니다. 여러 규칙이 일치하면 마지막 일치 항목 만 유지되고 이전 규칙은 무시됩니다. 규칙을 정의 할 때 사전에 규칙의 순서를 생각할 때이를 명심하십시오.
또한 원하는 경우 규칙 정규 표현식 문자열을 구성 파일로 이동하여 거기에서 읽을 수 있습니다. 나는 그 부분을 너에게 맡길 것이다.
Yikes ... 이미 사용 가능한 옵션이 있습니다. [Here 's] (http://www.hanselman.com/blog/AnIPAddressBlockingHttpModuleForASPNETIn9Minutes.aspx)가 있습니다. IP 주소 표준에 대해 조금 배우고 싶을 수도 있습니다. 그들은 당신의 직업을 훨씬 단순하게 만들 수 있습니다. (처음 생각할 때 CIDR 표기법이라고 생각합니다.) –
@ M.Babcock : 당신이 연결된 예제가 블록이 아니라 개별 IP 주소를 사용하고 있기 때문에 192.168.0.0/16 또는 뭔가를 차단하려는 경우 다루기 힘들어 질 것이라고 생각합니다. – Chris
매우 중복되지는 않지만 http : /stackoverflow.com/questions/1499269/how-to-check-if-an-ip-address-is-within-a-particular-subnet이 원하는 정보를 제공해야합니다 ... 주요 차이점은 그들이 사용하는 다른 표기법을 배우는데 – Chris