【发布时间】:2018-12-06 17:43:02
【问题描述】:
我的目标:我想 ping 每个 IPv4 地址并记录他们是否响应。
我设置它的方式是每个 IP 地址都对应一个索引。例如 0.0.0.0 是索引 0,0.0.1.0 是索引 256。所以如果 0.0.0.0 响应,那么位数组的第 0 个元素为真。
代码如下:
import subprocess
from bitarray import bitarray
import threading
import time
response_array = bitarray(256 * 256 * 256 * 256)
response_array.setall(False)
def send_all_pings():
index = 0
for f1 in range(256):
for f2 in range(256):
for f3 in range(256):
for f4 in range(256):
thread = PingerThread(".".join(map(str, [f1, f2, f3, f4])), index)
thread.start()
index += 1
time.sleep(30)
print("Writing response array to file")
with open('responses.bin', 'wb') as out:
response_array.tofile(out)
class PingerThread(threading.Thread):
def __init__(self, address, index):
threading.Thread.__init__(self)
self.address = address
self.index = index
def run(self):
if subprocess.call(["ping", "-c", "1", "-w", "1", self.address]) == 0:
response_array[self.index] = True
else:
response_array[self.index] = False
我能做些什么来让它运行得更快?欢迎任何优化,即使非常小!
谢谢
【问题讨论】:
-
最好的优化形式是与代码无关的优化:缩小范围!您可能已经知道,但没有任何场景可以 ping 所有数十亿个 IP 地址。先限制网络的范围,然后看看你对执行时间是否满意:)
-
nmap具有扫描大地址范围的功能……
标签: python python-3.x multithreading performance optimization