from ipaddress import ip_address, ip_network
1. ip_address
In [1]: from ipaddress import ip_address
In [3]: ip_address('192.168.0.1')
Out[3]: IPv4Address('192.168.0.1')
In [4]: ip_address('192.168.0.1').version
Out[4]: 4
In [5]: ip_address('fe::1').version
Out[5]: 6
In [6]: ip_address('fe::1')
Out[6]: IPv6Address('fe::1')
In [7]:
2. ip_network
In [13]: ip_network('192.168.0.1/24', strict=0)
Out[13]: IPv4Network('192.168.0.0/24')
In [14]: ip_network('192.168.0.1/24')
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-14-32e4baec665a> in <module>
----> 1 ip_network('192.168.0.1/24')
/usr/local/python/lib/python3.6/ipaddress.py in ip_network(address, strict)
72 """
73 try:
---> 74 return IPv4Network(address, strict)
75 except (AddressValueError, NetmaskValueError):
76 pass
/usr/local/python/lib/python3.6/ipaddress.py in __init__(self, address, strict)
1517 if packed & int(self.netmask) != packed:
1518 if strict:
-> 1519 raise ValueError('%s has host bits set' % self)
1520 else:
1521 self.network_address = IPv4Address(packed &
ValueError: 192.168.0.1/24 has host bits set
In [15]: ip_network('192.168.0.0/24')
Out[15]: IPv4Network('192.168.0.0/24')
In [16]: network = ip_network('192.168.0.0/24')
In [17]: network.num_addresses
Out[17]: 256
In [20]: for x in network.hosts(): # 所有可用ip
...: print(x)
...:
192.168.0.1
192.168.0.2
192.168.0.3
192.168.0.4
192.168.0.5
192.168.0.6
...
192.168.0.254
In [22]: [x for x in network.hosts()][0]
Out[22]: IPv4Address('192.168.0.1')
In [23]: [x for x in network.hosts()][-1]
Out[23]: IPv4Address('192.168.0.254')
In [24]: ip_network('192.168.0.1/24', strict=0)
Out[24]: IPv4Network('192.168.0.0/24')
In [25]: ip_network('192.168.0.1/24', strict=0).netmask
Out[25]: IPv4Address('255.255.255.0')
In [26]: ip_network('192.168.0.1/24', strict=0).hostmask
Out[26]: IPv4Address('0.0.0.255')
In [27]: ip_network('192.168.0.1/24', strict=0).network_address
Out[27]: IPv4Address('192.168.0.0')
In [28]: ip_network('192.168.0.1/24', strict=0).broadcast_address
Out[28]: IPv4Address('192.168.0.255')
3. ip_interface
In [30]: from ipaddress import ip_interface
In [31]: ip_interface('192.168.1.1/24')
Out[31]: IPv4Interface('192.168.1.1/24')
In [32]: ip_interface('192.168.1.1/24').network
Out[32]: IPv4Network('192.168.1.0/24')
In [34]: net = ip_interface('192.168.1.1/24').network
In [35]: net.num_addresses
Out[35]: 256
In [38]: ip_interface('192.168.1.1/24').network.num_addresses
Out[38]: 256