Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 708
DaveUK Avatar asked May 09 '11 05:05

DaveUK


1 Answers

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! }
like image 62
TCS Avatar answered Nov 15 '22 04:11

TCS