简体   繁体   中英

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

I want to convert this to cidr notation 1.2.3.4/24

How do I do this in Python3?

Use the ipaddress module in the standard library.


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; I'll assume it's an interface, so use 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:

>>> 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:

>>> 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.

You can use the IPy library to do this. If you scroll down to the documentation you can see the string conversions it can do. The one we're after is strNormal(1)

IP("1.2.3.4/255.255.255.0").strNormal(1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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