ショートバージョン:
import ipaddress
net=ipaddress.ip_network(u'1.0.0.0/8')
first=str(net[1])
last=str(net[-2])
ロングバージョン:
これは最初の計算の3つの方法を示す選択肢が+/- 10マイクロ秒
はtimeit/24のネットワークでありますipaddressを使用してCIDRブロックに最後に使用可能なIPアドレス を追加します。
と、それ以外の2つのホストイテレータを使用している は、古典的な宇宙時間のトレードオフを示しています。
import ipaddress
import time
import sys
#
# The fast, memory efficient way
#
start = time.time()
net=ipaddress.ip_network(u'1.0.0.0/8')
first=str(net[1])
last=str(net[-2])
stop = time.time()
seconds=stop-start
size=sys.getsizeof(net)
print("First Host: %s, Last Host: %s, Seconds: %.4f, Size (Mb): %d" % (first,last, seconds, size/(1024**2)))
#
# Space efficient, but slow
#
start = time.time()
net=ipaddress.ip_network(u'1.0.0.0/8')
iterator=ipaddress.ip_network(u'1.0.0.0/8').hosts()
first = last = next(iterator, None)
for last in iterator:
pass
first=str(first)
last=str(last)
stop = time.time()
seconds=stop-start
size=sys.getsizeof(net)
print("First Host: %s, Last Host: %s, Seconds: %.4f, Size (Mb): %d" % (first,last, seconds, size/(1024**2)))
#
# Memory hog and slow, the worst of both worlds.
#
start = time.time()
hosts=list(ipaddress.ip_network(u'1.0.0.0/8').hosts())
first_host=str(hosts[0])
last_host=str(hosts[-1])
size=sys.getsizeof(hosts)
stop = time.time()
seconds=stop-start
print("First Host: %s, Last Host: %s, Seconds: %.4f, Size (Mb): %d" % (first,last, seconds, size/(1024**2)))
First Host: 1.0.0.1, Last Host: 1.255.255.254, Seconds: 0.0000, Size (Mb): 0
First Host: 1.0.0.1, Last Host: 1.255.255.254, Seconds: 8.0086, Size (Mb): 0
First Host: 1.0.0.1, Last Host: 1.255.255.254, Seconds: 11.8096, Size (Mb): 132
'ip'は既にリストの中の単一のIPです。あなたは' ip [1] 'が返すと思いますか? – Barmar