Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Restricting an IP if it is between an IP Range

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.

like image 732
royse41 Avatar asked Dec 06 '22 04:12

royse41


2 Answers

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;
    }
}
like image 123
Espo Avatar answered Dec 28 '22 08:12

Espo


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.

like image 43
Kaleb Brasee Avatar answered Dec 28 '22 07:12

Kaleb Brasee