[英]how do you convert to cidr in python3?
I have an ip address 1.2.3.4 with a subnet mask 255.255.255.0 我的IP地址为1.2.3.4,子网掩码为255.255.255.0
I want to convert this to cidr notation 1.2.3.4/24 我想将此转换为cidr符号1.2.3.4/24
How do I do this in Python3? 如何在Python3中执行此操作?
Use the ipaddress
module in the standard library. 使用标准库中的
ipaddress
模块。
An address plus a netmask is either a network or an interface, not an address. 地址加上网络掩码是网络或接口,而不是地址。 Given that you've got some of the host bits set (it's 1.2.3.4, not 1.2.3.0), either you've got an interface, or you've got a non-canonical name for a network;
假设您已经设置了一些主机位(它是1.2.3.4,而不是1.2.3.0),那么您要么拥有接口,要么拥有网络的非规范名称。 I'll assume it's an interface, so use
ip_interface
: 我假设它是一个接口,所以使用
ip_interface
:
>>> i = ipaddress.ip_interface('1.2.3.4/255.255.255.0')
Or, if you want to make sure it's explicitly IPv4 not IPv6: 或者,如果您要确保它明确是IPv4而不是IPv6:
>>> i = ipaddress.IPv4Interface('1.2.3.4/255.255.255.0')
Or you can compose it out of an address and a network, instead of out of a combined string. 或者,您也可以使用地址和网络来组成它,而不用组合字符串来组成它。 It depends on what format you have this information in and what makes sense to you.
这取决于您以何种格式获取此信息以及什么对您有意义。
To get the CIDR format, use the with_prefixlen
accessor: 要获取CIDR格式,请使用
with_prefixlen
访问器:
>>> i.with_prefixlen
'1.2.3.4/24'
You can also do all kinds of other nifty things—extract the address ( 1.2.3.4
) as i.address
, or the network ( 1.2.3.0/24
) as i.network
, or enumerate all the addresses on the network by treating i.network
as a sequence, etc. 您还可以进行其他各种
i.address
操作-将地址( 1.2.3.4
)提取为i.address
,或将网络( 1.2.3.0/24
) i.network
为i.network
,或者通过将i.network
枚举来枚举网络上的所有地址。 i.network
作为序列,等等。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.