简体   繁体   English

如何使用netaddr在Python中将子网掩码转换为cidr

[英]How use netaddr to convert subnet mask to cidr in Python

How can I convert a ipv4 subnet mask to cidr notation using netaddr library? 如何使用netaddr库将ipv4子网掩码转换为cidr表示法?
Example: 255.255.255.0 to /24 示例: 255.255.255.0 to /24

Using netaddr : 使用netaddr

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

Using ipaddress from stdlib: 使用stdlib的ipaddress

>>> 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: 您也可以在不使用任何库的情况下执行此操作:只需在网络掩码的二进制表示中计算1位:

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

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('.')])

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. 它在某些方面类似于IAmSurajBobade的方法,但反过来查找相反。 It represents the way I would do the conversion manually by pen and paper. 它代表了我用笔和纸手动转换的方式。

As of Python 3.5: 从Python 3.5开始:

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

will print: 将打印:

24 24
0.0.0.0/24 0.0.0.0/24

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM