C# - 确定 IP 地址范围是否包含特定地址
在 C# 中,假设您有一个表示为字符串值的 IP 地址范围:
“192.168.1.1-192.168.2.30”
,并且您还有一个表示为字符串值的 IP 地址,例如:
192.168.1.150”
“ 确定地址范围是否包含单个 IP 地址的最优雅方法?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
将IP转换为32位整数(IP是4字节,因此也可以表示为整数)。
检查范围只是检查给定的 IP (int) 是否位于其他两个 IP(另外 2 个 int)之间。
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).
我刚刚写了一个小库 IpSet 来检查指定的 IP 地址是否包含在预定义的范围内。
同时支持 IPv4 和 IPv6。
支持 CIDR 表示法。
底层工作是将IP地址转换为整数并进行比较。
I just wrote a small library IpSet to check if the specified IP address is contained by a pre-defined range.
Support both IPv4 and IPv6.
Support CIDR notation.
The underlying work is convert IP addresses to integers and compare them.