Why python3 ipaddress module says that an address (172.16.32.5) in a network (172.16.0.0/12) when it doesn't?

59 views Asked by At

I'm setting a filter that runs some code if an IPv4 Address is not in an address range, I'm using ipaddress python3's module, but this is confusing me a lot, because it says that 172.16.32.5 is in the CIDR 172.16.0.0/12, when this is false:

Python 3.9.2 (default, Feb 28 2021, 17:03:44)
[GCC 10.2.1 20210110] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from ipaddress import IPv4Address,IPv4Network
>>> ip_addr = IPv4Address('172.16.32.5')
>>> ip_net = IPv4Network('172.16.0.0/12')
>>> all_addr = list(ip_net.hosts())
>>> ip_addr in ip_net
True
>>> all_addr[-1]
IPv4Address('172.31.255.254')

As you can see, the ip_addr is beyond the last host in that network...

What I'm doing wrong? Is there a bug in this module?

3

There are 3 answers

0
TessellatingHeckler On

A /12 subnet mask means the first 12 bits are set in the binary view. The subnet and the host you are querying have the same first 12 bits:

                         cutoff at 12 bits
/12 mask    11111111.1111 | 0000.00000000.00000000
172.16.0.0  10101100.0001 | 0000.00000000.00000000
172.16.32.5 10101100.0001 | 0000.00100000.00000101

172.32.16.5 10101100.0010 | 0000.00010000.00000101

The last one is what I think you are misreading it as, which has different first 12 bits, and would be outside the subnet.

See also: http://jodies.de/ipcalc?host=172.16.0.0&mask1=12&mask2=

0
Gbox4 On

Use a subnet calculator to make sure that you have the right outputs. This input into the calculator shows that, like TessellatingHeckler says, 172.16.0.0/12 goes up to 172.31.255.254. The CIDR you're looking for is 172.16.0.0/19, which goes up to 172.16.31.254.

0
Necrosaro On

I've just doublechecked and saw that I was not aware that the comparision was at a different octet, sorry, everything is fine then. :(