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
  • 1,440
  • 3
  • 18
  • 31
  • Does this answer your question? [How to check a input IP fall in a specific IP range](https://stackoverflow.com/questions/2138706/how-to-check-a-input-ip-fall-in-a-specific-ip-range) – Michael Freidgeim May 01 '22 at 21:25

2 Answers2

14

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,790
  • 5
  • 54
  • 86
  • 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
4

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
  • 544
  • 4
  • 13