简体   繁体   中英

C# - Determine if an IP address range contains a particular address

In C#, assume that you have an IP address range represented as a string value:

"192.168.1.1-192.168.2.30"

and you also have a single IP address represented as a string value like:

"192.168.1.150"

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

Cast the IP to 32bit integer (IP is 4 bytes, so it could be also represented as an integer). Than checking the range is simply checking if the given IP (int) is between two other IPs (2 other ints).

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

I just wrote a small library IpSet to check if the specified IP address is contained by a pre-defined 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 both IPv4 and IPv6. Support CIDR notation. The underlying work is convert IP addresses to integers and compare them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM