7

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?

DaveUK
  • 910
  • 1
  • 12
  • 25

2 Answers2

13

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! }
TCS
  • 5,350
  • 4
  • 39
  • 75
  • Excellent idea. And for the lazy, (*grin*) here is a SO answer that should help with that: http://stackoverflow.com/questions/461742/how-to-convert-an-ipv4-address-into-a-integer-in-c – Dan Esparza Sep 07 '12 at 17:49
3

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.

DonnyTian
  • 464
  • 4
  • 11