Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ip Range control on c# [duplicate]

Tags:

c#

ip

I have an IP range which is formed "from" and "to"

From: 127.0.0.1 to: 127.0.0.255 etc.

How can I control the sended Ip which is 127.0.1.253? Is it inside of Ip range?

like image 996
Stack Over Avatar asked Feb 16 '23 18:02

Stack Over


1 Answers

Convert the IPs to an integer, and check whether it fits within the range.

  • 127.0.0.1 = 2130706433
  • 127.0.0.255 = 2130706687

  • 127.0.1.253 = 2130706941

Hence it doesn't fit within the range.


 public static long IP2Long(string ip)
   {
       string[] ipBytes;
       double num = 0;
       if(!string.IsNullOrEmpty(ip))
       {
           ipBytes = ip.Split('.');
           for (int i = ipBytes.Length - 1; i >= 0; i--)
           {
               num += ((int.Parse(ipBytes[i]) % 256) * Math.Pow(256, (3 - i)));
           }
       }
       return (long)num;
   }

Source: http://geekswithblogs.net/rgupta/archive/2009/04/29/convert-ip-to-long-and-vice-versa-c.aspx


Therefore using this method you could do something like:

long start = IP2Long("127.0.0.1");
long end = IP2Long("127.0.0.255");
long ipAddress = IP2Long("127.0.1.253");

bool inRange = (ipAddress >= start && ipAddress <= end);

if (inRange){
  //IP Address fits within range!
}
like image 118
Curtis Avatar answered Feb 24 '23 00:02

Curtis