Python function to determine if a given IPv4 CIDR fits into another.
How cidr_fit(cidr_a,cidr_b)
works:
- For both CIDR's given:
- Splits each CIDR into address and prefix size parts.
- Converts the address part to a 32 bit binary string.
- Example:
192.168.0.1
becomes11000000101010000000000000000001
.
- Example:
- Cuts out everything after the prefix size.
- Example:
192.168.0.1/12
becomes110000001010
.
- Example:
- Now check if either:
- Remaining binary string A starts with B, or...
- Remaining binary string B starts with A
- Done.
Using an example CIDR list of Google API ranges from _spf.google.com
against a Google IP of 216.58.196.138
:
$ ./cidrfit.py
('108.177.8.0/21 ', False)
('108.177.96.0/19 ', False)
('130.211.0.0/22 ', False)
('172.217.0.0/19 ', False)
('172.217.128.0/19 ', False)
('172.217.160.0/20 ', False)
('172.217.192.0/19 ', False)
('172.217.32.0/20 ', False)
('173.194.0.0/16 ', False)
('209.85.128.0/17 ', False)
('216.239.32.0/19 ', False)
('216.58.192.0/19 ', True)
('35.190.247.0/24 ', False)
('35.191.0.0/16 ', False)
('64.233.160.0/19 ', False)
('66.102.0.0/20 ', False)
('66.249.80.0/20 ', False)
('72.14.192.0/18 ', False)
('74.125.0.0/16 ', False)