Reputation: 2994
Need is simple: from a single IPv4 address in cidr format (e.g.: "192.168.80.22/24") extract relevant info:
Is there an "easy way" to do this ("easy", in this context means "without actually coding a parser"), possibly using just the Python Standard Library (I think ipaddress
can't do this, but I might have misread docs)
Reason why I think ipaddress
can't handle this is I tried:
>>> import ipaddress
>>> ip = ipaddress.ip_address("192.168.80.22/24")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python3.9/ipaddress.py", line 53, in ip_address
ValueError: '192.168.80.22/24' does not appear to be an IPv4 or IPv6 address
>>> ip = ipaddress.ip_address("192.168.80.22")
>>> ip = ipaddress.ip_network("192.168.80.22/24")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python3.9/ipaddress.py", line 74, in ip_network
File "/usr/lib/python3.9/ipaddress.py", line 1504, in __init__
ValueError: 192.168.80.22/24 has host bits set
>>> ip = ipaddress.ip_network("192.168.80.0/24")
Apparently host addresses and net addresses do not mix
Upvotes: 0
Views: 214
Reputation: 1979
You can use ipaddress.ip_interface
as follows:
>>> import ipaddress
>>>
>>> host4 = ipaddress.ip_interface("192.168.80.22/24")
>>>
>>> host4.ip
IPv4Address('192.168.80.22') # address
>>> host4.network.network_address
IPv4Address('192.168.80.0') # network
>>> host4.netmask
IPv4Address('255.255.255.0') # netmask
>>> host4.network.broadcast_address
IPv4Address('192.168.80.255') # broadcast
Upvotes: 1