C # - determine if a range of IP addresses contains a specific address

In C #, suppose you have a range of IP addresses represented as a string value:

"192.168.1.1-192.168.2.30"

and you also have one IP address presented as a string value, for example:

"192.168.1.150"

What would be the most elegant way to determine if a range of addresses contains a single IP address?

+6
source share
2 answers

Transmission from IP to 32-bit integer (IP is 4 bytes, so it can also be represented as an integer). Then the range check simply checks if the given IP (int) is between two other IP addresses (2 other ints).

if( low_range <= checked_ip <= high_range ){ TRUE! } 
+12
source

I just wrote a small IpSet library to check if the specified IP address is in a predefined range.

 var set = IpSet.ParseOrDefault("192.168.0.*,10.10.1.0/24,192.168.1.1-192.168.2.30"); var result = set.Contains("192.168.1.150"); // true 

Support for both IPv4 and IPv6. Support CIDR Recording. The main job is to convert IP addresses to integers and compare them.

0
source

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


All Articles