How use netaddr to convert subnet mask to cidr in Python

孤街浪徒 提交于 2019-12-22 03:20:59

问题


How can I convert a ipv4 subnet mask to cidr notation using netaddr library?
Example: 255.255.255.0 to /24


回答1:


Using netaddr:

>>> from netaddr import IPAddress
>>> IPAddress('255.255.255.0').netmask_bits()
24

Using ipaddress from stdlib:

>>> from ipaddress import IPv4Network
>>> IPv4Network('0.0.0.0/255.255.255.0').prefixlen
24

You can also do it without using any libraries: just count 1-bits in the binary representation of the netmask:

>>> netmask = '255.255.255.0'
>>> sum(bin(int(x)).count('1') for x in netmask.split('.'))
24



回答2:


>>> IPNetwork('0.0.0.0/255.255.255.0').prefixlen
24



回答3:


Use the following function. it is fast, reliable, and don't use any library.

# code to convert netmask ip to cidr number
def netmask_to_cidr(netmask):
    '''
    :param netmask: netmask ip addr (eg: 255.255.255.0)
    :return: equivalent cidr number to given netmask ip (eg: 24)
    '''
    return sum([bin(int(x)).count('1') for x in netmask.split('.')])



回答4:


How about this one? It does not need any additional library as well.

def translate_netmask_cidr(netmask):
    """
    Translate IP netmask to CIDR notation.
    :param netmask:
    :return: CIDR netmask as string
    """
    netmask_octets = netmask.split('.')
    negative_offset = 0

    for octet in reversed(netmask_octets):
        binary = format(int(octet), '08b')
        for char in reversed(binary):
            if char == '1':
                break
            negative_offset += 1

    return '/{0}'.format(32-negative_offset)

It is in some ways similar to IAmSurajBobade's approach but instead does the lookup reversed. It represents the way I would do the conversion manually by pen and paper.




回答5:


As of Python 3.5:

ip4 = ipaddress.IPv4Network((0,'255.255.255.0'))
print(ip4.prefixlen)
print(ip4.with_prefixlen)

will print:

24
0.0.0.0/24



来源:https://stackoverflow.com/questions/38085571/how-use-netaddr-to-convert-subnet-mask-to-cidr-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!