Python 使用标准库处理 cidr 网络地址

Python cidr net address handling with standard lib

需要很简单:从单个 cidr 格式的 IPv4 地址(例如:“192.168.80.22/24”)提取相关信息:

是否有一种“简单的方法”来做到这一点(“简单”,在这种情况下意味着“无需实际编写解析器”),可能只使用 Python 标准库(我 think ipaddress 不能这样做,但我可能误读了文档)

认为 ipaddress 无法处理的原因是我尝试过:

>>> 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")

显然主机地址和网络地址不能混用

您可以按如下方式使用ipaddress.ip_interface

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