Reputation: 7548
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.
Upvotes: 0
Views: 1249
Reputation: 46
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'
Upvotes: 3