IP falls in CIDR range

后端 未结 2 607
忘了有多久
忘了有多久 2021-02-10 12:16

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 t

相关标签:
2条回答
  • 2021-02-10 12:48

    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.

    0 讨论(0)
  • 2021-02-10 13:03

    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);
    
    0 讨论(0)
提交回复
热议问题