[英]IP falls in CIDR range
I have an IP like this: 12.12.12.12 我有这样的IP:12.12.12.12
I'm looping through different IP ranges (in 12.12.12.0/24 (example)) format, and trying to see if the IP is in the range. 我循环遍历不同的IP范围(12.12.12.0/24(示例))格式,并尝试查看IP是否在范围内。
I have tried various methods such as inet_addr and comparing but I can't seem to get it. 我尝试了各种方法,如inet_addr和比较,但我似乎无法得到它。
Is there an easy way to do this? 是否有捷径可寻? I'm using Windows. 我正在使用Windows。
Just test whether: 只测试是否:
(ip & netmask) == (range & netmask)
You can determine the netmask from the CIDR parameters range/netbits
as follows: 您可以从CIDR参数range/netbits
确定网络掩码,如下所示:
uint32_t netmask = ~(~uint32_t(0) >> netbits);
Take the binary representation and zero out what is not matching your network mask. 获取二进制表示并将与网络掩码不匹配的内容归零。
Clarification: Let's say you have the IP abcd
and want to match it to efgh/i
then, you can throw the IP into one unsigned integer, uint32_t ip = a<<24 + b<<16 + c<<8 + d
and do the same with uint32_t range = e<<24 + f<<16 + g<<8 + h
. 澄清:假设您有IP abcd
并希望将其与efgh/i
匹配,那么您可以将IP转换为一个无符号整数, uint32_t ip = a<<24 + b<<16 + c<<8 + d
uint32_t range = e<<24 + f<<16 + g<<8 + h
。 Now you can use your network mask: uint32_t mask = (~0u) << (32-i)
. 现在您可以使用网络掩码: uint32_t mask = (~0u) << (32-i)
。 Now, you can simply check if ip
"is in" range
by comparing them: ip & mask == range & mask
. 现在,您可以通过比较它们来检查ip
“是否在” range
: ip & mask == range & mask
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.