W3Cschool
恭喜您成為首批注冊(cè)用戶
獲得88經(jīng)驗(yàn)值獎(jiǎng)勵(lì)
你有一個(gè)CIDR網(wǎng)絡(luò)地址比如“123.45.67.89/27”,你想將其轉(zhuǎn)換成它所代表的所有IP (比如,“123.45.67.64”, “123.45.67.65”, …, “123.45.67.95”))
可以使用?<span class="pre" style="box-sizing: border-box;">ipaddress</span>
?模塊很容易的實(shí)現(xiàn)這樣的計(jì)算。例如:
>>> import ipaddress
>>> net = ipaddress.ip_network('123.45.67.64/27')
>>> net
IPv4Network('123.45.67.64/27')
>>> for a in net:
... print(a)
...
123.45.67.64
123.45.67.65
123.45.67.66
123.45.67.67
123.45.67.68
...
123.45.67.95
>>>
>>> net6 = ipaddress.ip_network('12:3456:78:90ab:cd:ef01:23:30/125')
>>> net6
IPv6Network('12:3456:78:90ab:cd:ef01:23:30/125')
>>> for a in net6:
... print(a)
...
12:3456:78:90ab:cd:ef01:23:30
12:3456:78:90ab:cd:ef01:23:31
12:3456:78:90ab:cd:ef01:23:32
12:3456:78:90ab:cd:ef01:23:33
12:3456:78:90ab:cd:ef01:23:34
12:3456:78:90ab:cd:ef01:23:35
12:3456:78:90ab:cd:ef01:23:36
12:3456:78:90ab:cd:ef01:23:37
>>>
<span class="pre" style="box-sizing: border-box;">Network</span>
?也允許像數(shù)組一樣的索引取值,例如:
>>> net.num_addresses
32
>>> net[0]
IPv4Address('123.45.67.64')
>>> net[1]
IPv4Address('123.45.67.65')
>>> net[-1]
IPv4Address('123.45.67.95')
>>> net[-2]
IPv4Address('123.45.67.94')
>>>
另外,你還可以執(zhí)行網(wǎng)絡(luò)成員檢查之類的操作:
>>> a = ipaddress.ip_address('123.45.67.69')
>>> a in net
True
>>> b = ipaddress.ip_address('123.45.67.123')
>>> b in net
False
>>>
一個(gè)IP地址和網(wǎng)絡(luò)地址能通過一個(gè)IP接口來指定,例如:
>>> inet = ipaddress.ip_interface('123.45.67.73/27')
>>> inet.network
IPv4Network('123.45.67.64/27')
>>> inet.ip
IPv4Address('123.45.67.73')
>>>
<span class="pre" style="box-sizing: border-box;">ipaddress</span>
?模塊有很多類可以表示IP地址、網(wǎng)絡(luò)和接口。 當(dāng)你需要操作網(wǎng)絡(luò)地址(比如解析、打印、驗(yàn)證等)的時(shí)候會(huì)很有用。
要注意的是,<span class="pre" style="box-sizing: border-box;">ipaddress</span>
?模塊跟其他一些和網(wǎng)絡(luò)相關(guān)的模塊比如?<span class="pre" style="box-sizing: border-box;">socket</span>
?庫(kù)交集很少。 所以,你不能使用?<span class="pre" style="box-sizing: border-box;">IPv4Address</span>
?的實(shí)例來代替一個(gè)地址字符串,你首先得顯式的使用?<span class="pre" style="box-sizing: border-box;">str()</span>
?轉(zhuǎn)換它。例如:
>>> a = ipaddress.ip_address('127.0.0.1')
>>> from socket import socket, AF_INET, SOCK_STREAM
>>> s = socket(AF_INET, SOCK_STREAM)
>>> s.connect((a, 8080))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: Can't convert 'IPv4Address' object to str implicitly
>>> s.connect((str(a), 8080))
>>>
更多相關(guān)內(nèi)容,請(qǐng)參考?An Introduction to the ipaddress Module
Copyright©2021 w3cschool編程獅|閩ICP備15016281號(hào)-3|閩公網(wǎng)安備35020302033924號(hào)
違法和不良信息舉報(bào)電話:173-0602-2364|舉報(bào)郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號(hào)
聯(lián)系方式:
更多建議: