Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IP Range to CIDR conversion in Python?

Tags:

How can I get a CIDR notation representing a range of IP addresses, given the start and end IP addresses of the range, in Python? I can find CIDR to IP Range but cannot find any code for the reverse.

Example of the desired output:

startip = '63.223.64.0'
endip = '63.223.127.255'

return '63.223.64.0/18'
like image 734
Chris Hall Avatar asked Jun 13 '14 22:06

Chris Hall


People also ask

How do you calculate CIDR from IP range?

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.

How many IPS are in CIDR range?

0.0 to 127.255. 255.255 , with a default mask of 255.0. 0.0 (or /8 in CIDR). This means that Class A addressing can have a total of 128 (27) networks and 16,777,214 (224-2) usable addresses per network.

What is IP CIDR notation?

CIDR notation is a compact representation of an IP address and its associated network mask. The notation was invented by Phil Karn in the 1980s. CIDR notation specifies an IP address, a slash ('/') character, and a decimal number.


2 Answers

Starting Python 3.3 the bundled ipaddress can provide what you want. The function summarize_address_range returns an iterator with the networks resulting from the start, end you specify:

>>> import ipaddress
>>> startip = ipaddress.IPv4Address('63.223.64.0')
>>> endip = ipaddress.IPv4Address('63.223.127.255')
>>> [ipaddr for ipaddr in ipaddress.summarize_address_range(startip, endip)]
[IPv4Network('63.223.64.0/18')]
like image 174
MichielB Avatar answered Sep 20 '22 06:09

MichielB


You may use iprange_to_cidrs provided by netaddr module. Example:

pip install netaddr
import netaddr
cidrs = netaddr.iprange_to_cidrs(startip, endip)

Here are the official docs: https://netaddr.readthedocs.io/

like image 33
ρss Avatar answered Sep 22 '22 06:09

ρss