Ok, it's friday afternoon, and i've had a long week so would appreciate some help! Currently, i have a list of IP ranges, as follows:
List<IPRange> ipRanges = new List<IPRange>();
ipRanges.Add(new IPRange { From = "145.36.0.0", To = "145.36.255.255" });
ipRanges.Add(new IPRange { From = "194.183.227.184", To = "194.183.227.191" });
ipRanges.Add(new IPRange { From = "193.131.192.0", To = "193.131.223.255" });
After getting the IP of the client, if it falls anywhere between these sets of ranges, they need to be redirected elsewhere.
For example,
If someone visited the site with the IP 192.168.0.1
, they would be allowed access.
If they visited with 145.36.1.0
, they would not be allowed access because it falls between the first range in that list.
I could split each IP by the period, and work out where the range starts to change, then do a comparison, but that would be heavy on the server.
I know IP's are basically just decimal numbers, but am not really sure how that works.
Has anyone come across this before?
Cheers, Sean.
Convert Each IP-address to number, and then check if the user ip address is between those numbers.
public double Dot2LongIP(string DottedIP)
{
int i;
string [] arrDec;
double num = 0;
if (DottedIP == "")
{
return 0;
}
else
{
arrDec = DottedIP.Split('.');
for(i = arrDec.Length - 1; i >= 0 ; i --)
{
num += ((int.Parse(arrDec[i])%256) * Math.Pow(256 ,(3 - i )));
}
return num;
}
}
I would convert the IP addresses to 32-bit numbers and then do a simple >= From and <= To check to see if it's in range.
For example, 192.168.1.1 -> 192 * 256^3 + 168 * 256^2 + 1 * 256 + 1.
Working with your values, 145.36.0.0 -> 2435055616 and 145.36.0.0 -> 2435121151. So 145.36.200.30 -> 2435106846, and falls in that range, so it's valid. But 145.35.255.255 -> 2435055615 is not in the range (just barely), so it fails.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With