標準庫ipaddress從Python 3.3開始出現,其中提供的方法和類可以用於建立操作IPv4和IPv6的地址和網路。
1.統一的建立IP地址、網路和介面的方法
ipaddress.ip_address('myaddress') ipaddress.ip_network('myaddress', strict=True) ipaddress.ip_interface('myaddress') 2.IP地址類
class ipaddress.IPv4Address('myaddress') class ipaddress.IPv6Address('myaddress') 可以將一個IP地址對象轉換為一個字串,樣本如下:
str(ipaddress.IPv4Address('myaddress'))
3.IP網路類
class ipaddress.IPv4Network('myaddress', strict=True) 預設掩碼為'/32'
預設strict=True,表示校正'myaddress'中的掩碼位(或主機位),如果'myaddress'的IP與'myaddress'中的掩碼位(或主機位)有衝突,則拋出異常ValueError: %s has host bits set。如果不想校正'myaddress'中的掩碼位(或主機位),可以設定strict=False。
class ipaddress.IPv6Network('myaddress', strict=True)
預設掩碼為'/128'
4.IP介面類一個介面可以具體表示某一個網路中的某一個IP地址。這樣就可以通過IP介面對象擷取一個IP地址對象,也可以擷取一個網路對象,方法如下:
my_interface.ip
my_interface.network
class ipaddress.IPv4Interface('myaddress') 擴充自IPv4Address
class ipaddress.IPv6Interface('myaddress') 擴充自IPv6Address
在Python的第三方擴充庫中,也有大量操作IPv4和IPv6的地址和網路的擴充包,如netaddr, IPy等,但是不推薦使用。
參考連結:
https://docs.python.org/3/library/ipaddress.html
https://github.com/python/cpython/tree/3.6/Lib/ipaddress.py
https://docs.python.org/3/howto/ipaddress.html