
- Python - 網路程式設計
- Python - 網路概述
- Python - 網路環境
- Python - 網際網路協議
- Python - IP 地址
- Python - DNS 查詢
- Python - 路由
- Python - HTTP 請求
- Python - HTTP 響應
- Python - HTTP 頭部
- Python - 自定義 HTTP 請求
- Python - 請求狀態碼
- Python - HTTP 認證
- Python - HTTP 資料下載
- Python - 連線重用
- Python - 網路介面
- Python - 套接字程式設計
- Python - HTTP 客戶端
- Python - HTTP 伺服器
- Python - 構建 URL
- Python - 網頁表單提交
- Python - 資料庫和 SQL
- Python - Telnet
- Python - 電子郵件
- Python - SMTP
- Python - POP3
- Python - IMAP
- Python - SSH
- Python - FTP
- Python - SFTP
- Python - Web 伺服器
- Python - 資料上傳
- Python - 代理伺服器
- Python - 目錄列表
- Python - 遠端過程呼叫
- Python - RPC JSON 伺服器
- Python - 谷歌地圖
- Python - RSS Feed
Python - IP 地址
IP 地址(網際網路協議)是網路中的一個基本概念,它提供了在網路中分配地址的能力。Python 模組ipaddress被廣泛用於驗證和分類 IP 地址為 IPv4 和 IPv6 型別。它還可以用於比較 IP 地址值以及進行 IP 地址算術運算來操作 IP 地址。
驗證 IPv4 地址
ip_address 函式驗證 IPv4 地址。如果值的範圍超出 0 到 255,則會丟擲錯誤。
print (ipaddress.ip_address(u'192.168.0.255')) print (ipaddress.ip_address(u'192.168.0.256'))
當我們執行上述程式時,我們會得到以下輸出:
192.168.0.255 ValueError: u'192.168.0.256' does not appear to be an IPv4 or IPv6 address
驗證 IPv6 地址
ip_address 函式驗證 IPv6 地址。如果值的範圍超出 0 到 ffff,則會丟擲錯誤。
print (ipaddress.ip_address(u'FFFF:9999:2:FDE:257:0:2FAE:112D')) #invalid IPV6 address print (ipaddress.ip_address(u'FFFF:10000:2:FDE:257:0:2FAE:112D'))
當我們執行上述程式時,我們會得到以下輸出:
ffff:9999:2:fde:257:0:2fae:112d ValueError: u'FFFF:10000:2:FDE:257:0:2FAE:112D' does not appear to be an IPv4 or IPv6 address
檢查 IP 地址型別
我們可以提供各種格式的 IP 地址,該模組將能夠識別有效的格式。它還會指示它是哪一類 IP 地址。
print type(ipaddress.ip_address(u'192.168.0.255')) print type(ipaddress.ip_address(u'2001:db8::')) print ipaddress.ip_address(u'192.168.0.255').reverse_pointer print ipaddress.ip_network(u'192.168.0.0/28')
當我們執行上述程式時,我們會得到以下輸出:
255.0.168.192.in-addr.arpa 192.168.0.0/28
IP 地址比較
我們可以對 IP 地址進行邏輯比較,以確定它們是否相等。我們還可以比較一個 IP 地址的值是否大於另一個 IP 地址的值。
print (ipaddress.IPv4Address(u'192.168.0.2') > ipaddress.IPv4Address(u'192.168.0.1')) print (ipaddress.IPv4Address(u'192.168.0.2') == ipaddress.IPv4Address(u'192.168.0.1')) print (ipaddress.IPv4Address(u'192.168.0.2') != ipaddress.IPv4Address(u'192.168.0.1'))
當我們執行上述程式時,我們會得到以下輸出:
True False True
IP 地址算術運算
我們還可以應用算術運算來操作 IP 地址。我們可以將整數加到或減去 IP 地址。如果加法後最後一個八位位元組的值超過 255,則前一個八位位元組會遞增以容納該值。如果額外值不能被任何前一個八位位元組吸收,則會引發 ValueError。
print (ipaddress.IPv4Address(u'192.168.0.2')+1) print (ipaddress.IPv4Address(u'192.168.0.253')-3) # Increases the previous octet by value 1. print (ipaddress.IPv4Address(u'192.168.10.253')+3) # Throws Value error print (ipaddress.IPv4Address(u'255.255.255.255')+1)
當我們執行上述程式時,我們會得到以下輸出:
192.168.0.3 192.168.0.250 192.168.11.0 AddressValueError: 4294967296 (>= 2**32) is not permitted as an IPv4 address
廣告