Python的標準庫ipaddress詳解

來源:互聯網
上載者:User

標準庫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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.