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

2

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?

Slab answered 9/5, 2011 at 5:13 Comment(1)
Does this answer your question? How to check a input IP fall in a specific IP rangeRenaissance
S
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! }
Severen answered 9/5, 2011 at 5:17 Comment(1)
Excellent idea. And for the lazy, (grin) here is a SO answer that should help with that: #462242Narcoma
R
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.

Ranged answered 19/12, 2017 at 2:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.