Python中如何使用netaddr将子网掩码转换为cidr
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38085571/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How use netaddr to convert subnet mask to cidr in Python
提问by Mik
How can I convert a ipv4 subnet mask to cidr notation using netaddr
library?
Example: 255.255.255.0 to /24
如何使用netaddr
库将 ipv4 子网掩码转换为 cidr 表示法?
例子: 255.255.255.0 to /24
回答by Eugene Yarmash
Using netaddr
:
使用netaddr
:
>>> from netaddr import IPAddress
>>> IPAddress('255.255.255.0').netmask_bits()
24
Using ipaddress
from stdlib:
ipaddress
从 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:
您也可以在不使用任何库的情况下执行此操作:只需计算网络掩码的二进制表示中的 1 位:
>>> netmask = '255.255.255.0'
>>> sum(bin(int(x)).count('1') for x in netmask.split('.'))
24
回答by Derek Chadwell
>>> IPNetwork('0.0.0.0/255.255.255.0').prefixlen
24
回答by IAmSurajBobade
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('.')])
回答by kb-0
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.
它在某些方面类似于 IAmSurajBobade 的方法,但查找相反。它代表了我用笔和纸手动进行转换的方式。
回答by gerardw
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
0.0.0.0/24
24
0.0.0.0/24