0

How do I convert a string ip, e.g. "1.2.3.4", to an ipaddress.ip_network with netmask "255.255.255.0", e.g. to get ip_network("1.2.3.0/24") using the ipaddress library. The aim is not to do any string manipulation of ips myself.

1 Answer 1

3

Simply add the option strict=False. In that case any host bits will be stripped to convert the interface address to a valid network address.

>>> from ipaddress import ip_network
>>>
>>> network = str(ip_network("1.2.3.4/255.255.255.0", strict=False))
>>> network
'1.2.3.0/24'

Skip the conversion back to a string if you want to keep the actual IPv4Network/IPv6Network object.

BTW, in case that you do want a string with both, host bits set and a mask, then you can use the "ip_interface" function from the ipaddress module. It will return an IPv4Interface object:

>>> from ipaddress import ip_interface
>>>
>>> interface = str(ip_interface("1.2.3.4/255.255.255.0"))
>>> interface
'1.2.3.4/24'
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.