Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IP falls in CIDR range

Tags:

c++

c

ip

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.

like image 589
seth Avatar asked Sep 26 '11 18:09

seth


People also ask

Does IP fall in CIDR range?

A CIDR IP address looks like a normal IP address except that it ends with a slash followed by a number, called the IP network prefix. CIDR addresses reduce the size of routing tables and make more IP addresses available within organizations.

How do I get IP range from CIDR?

The formula to calculate the number of assignable IP address to CIDR networks is similar to classful networking. Subtract the number of network bits from 32. Raise 2 to that power and subtract 2 for the network and broadcast addresses. For example, a /24 network has 232-24 - 2 addresses available for host assignment.

What is my IP in CIDR notation?

In CIDR notation, IP addresses are written as a prefix, and a suffix is attached to indicate how many bits are in the entire address. The suffix is set apart from the prefix with a slash mark. For instance, in the CIDR notation 192.0. 1.0/24, the prefix is 192.0.


2 Answers

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);
like image 166
Ben Voigt Avatar answered Sep 22 '22 16:09

Ben Voigt


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.

like image 33
bitmask Avatar answered Sep 26 '22 16:09

bitmask