Ip range control in C #

I have an IP range that is configured from to

From: 127.0.0.1 to: 127.0.0.255, etc.

How can I manage the modified Ip, which is 127.0.1.253? Is it within the ip range?

+4
source share
1 answer

Convert IP addresses to integer and check if it fits within range.

  • 127.0.0.1 = 2130706433
  • 127.0.0.255 = 2130706687

  • 127.0.1.253 = 2130706941

Therefore, it does not fit into 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 can 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! } 
+8
source

Source: https://habr.com/ru/post/1494044/


All Articles