IP falls in CIDR range

青春壹個敷衍的年華 提交于 2020-01-01 03:33:10

问题


I have an IP like this: 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.
I have tried various methods such as inet_addr and comparing but I can't seem to get it.
Is there an easy way to do this? I'm using Windows.


回答1:


Just test whether:

(ip & netmask) == (range & netmask)

You can determine the netmask from the CIDR parameters range/netbits as follows:

uint32_t netmask = ~(~uint32_t(0) >> netbits);



回答2:


Take the binary representation and zero out what is not matching your network mask.

Clarification: Let's say you have the IP a.b.c.d and want to match it to e.f.g.h/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. Now you can use your network mask: uint32_t mask = (~0u) << (32-i). Now, you can simply check if ip "is in" range by comparing them: ip & mask == range & mask.



来源:https://stackoverflow.com/questions/7559803/ip-falls-in-cidr-range

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!