Search code examples
pythoncidr

How to create CIDR IP address/Range in IPv4 in python?


How do I convert a IPv4 subnet mask to CIDR range? I have subnet and gateway information available.

Data available:

  • Subnet Mask: 255.255.255.0
  • Gateway: 192.0.2.250
  • Expected CIDR notation: 192.0.2.0/24

I know using ipaddress, CIDR value can be obtained.

from ipaddress import IPv4Network
ip4 = IPv4Network('0/255.255.255.0')
print(ip4.prefixlen)
print(ip4.with_prefixlen)

with results

24
0.0.0.0/24


Solution

  • Pass both your gateway and mask as a tuple to IPv4Network

    import ipaddress
    gateway = '192.0.2.250'
    mask = '255.255.255.0'
    network = ipaddress.IPv4Network((gateway, mask), strict=False)
    print(network) # 192.0.2.0/24
    

    You must pass strict=False because the network has host bits set