Search code examples
pythonstringlistmasksubnet

Is there a way of converting cidr to subnet mask in python ? I tried searching online but not getting the Exact answer


my output is

print (network)

['10.202.224.0/24', '10.4.40.0/23', '10.3.41.0/24', '10.4.42.0/21']

can this be somehow converted to

['10.202.224.0/255.255.255.0', '10.4.40.0/255.255.254.0', '10.4.41.0/255.255.255.0', '10.4.42.0/255.255.248.0']

anything that helps converting the cidr to mask.

Thanks in Advance


Solution

  • you can check out the python code for this may help you by clicking the link below:this is the link to follow

    and the code is:

    import socket
    import struct
    
    def cidr_to_netmask(cidr):
        network, net_bits = cidr.split('/')
        host_bits = 32 - int(net_bits)
        netmask = socket.inet_ntoa(struct.pack('!I', (1 << 32) - (1 << host_bits)))
        return network, netmask
    

    usage:

    >>> cidr_to_netmask('10.10.1.32/27')
    ('10.10.1.32', '255.255.255.224')
    >>> cidr_to_netmask('208.128.0.0/11')
    ('208.128.0.0', '255.224.0.0')
    >>> cidr_to_netmask('208.130.28.0/22')
    ('208.130.28.0', '255.255.252.0')