Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Need is simple: from a single IPv4 address in cidr format (e.g.: "192.168.80.22/24") extract relevant info:

  • address: "192.168.80.22"
  • network: "192.168.80.0"
  • netmask: "255.255.255.0"
  • broadcast: "192.168.80.255"

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

question from:https://stackoverflow.com/questions/65945471/python-cidr-net-address-handling-with-standard-lib

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
249 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...