IP falls into the range of CIDR

I have an IP address: 12/12/12/12
I am sorting through various IP ranges (in the format 12/12/12.0/24 (example)) and trying to check if the IP is in the range.
I tried various methods like inet_addr and comparison, but I can not get it.
Is there an easy way to do this? I am using windows.

+5
source share
2 answers

Just check if there is:

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

You can define a netmask from the CIDR parameters range/netbitsas follows:

uint32_t netmask = ~(~uint32_t(0) >> netbits);
+6
source

Take a binary representation and zero out what doesn't match your netmask.

: , IP a.b.c.d e.f.g.h/i, IP , uint32_t ip = a<<24 + b<<16 + c<<8 + d uint32_t range = e<<24 + f<<16 + g<<8 + h. : uint32_t mask = (~0u) << (32-i). , ip "" range, : ip & mask == range & mask.

+2

All Articles