简体   繁体   English

C# - 确定IP地址范围是否包含特定地址

[英]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: 在C#中,假设您有一个表示为字符串值的IP地址范围:

"192.168.1.1-192.168.2.30" “192.168.1.1-192.168.2.30”

and you also have a single IP address represented as a string value like: 并且您还有一个表示为字符串值的IP地址,如:

"192.168.1.150" “192.168.1.150”

What would be the most elegant way to determine if the address range contains the single IP address? 确定地址范围是否包含单个IP地址的最优雅方法是什么?

Cast the IP to 32bit integer (IP is 4 bytes, so it could be also represented as an integer). 将IP转换为32位整数(IP为4个字节,因此它也可以表示为整数)。 Than checking the range is simply checking if the given IP (int) is between two other IPs (2 other ints). 检查范围只是检查给定的IP(int)是否在两个其他IP(另外两个int)之间。

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. 我刚写了一个小库IpSet来检查指定的IP地址是否包含在预定义的范围内。

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. 支持IPv4和IPv6。 Support CIDR notation. 支持CIDR表示法。 The underlying work is convert IP addresses to integers and compare them. 基础工作是将IP地址转换为整数并进行比较。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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