C method of determining whether a given IP address is within the specified range

  • 2021-01-03 21:01:22
  • OfStack

This article example shows how C# determines whether a given IP address is within a specified range. Share to everybody for everybody reference. The specific analysis is as follows:

For example, given a section of ip: 127.0.0.1 ~ 127.0.0.255, we want to determine whether a given ip address is within this section. We can first convert the ip address into an integer, and then it is easy to compare the size of the integer.

Such as:
127.0.0.1 = 2130706433
127.0.0.255 = 2130706687

Judge:
127.0.1.253 = 2130706941
Whether within this range, you can directly compare the integer size

Convert THE ip address to an integer:


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;
}

Determines whether a given ip address is within the specified range:


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!
}

Hopefully this article has helped you with your C# programming.


Related articles: