My goal: I want to ping every single IPv4 address and record whether or not they responded.
The way I have it set up is every IP address corresponds to an index. For example 0.0.0.0
is index 0
and 0.0.1.0
is index 256
. So if 0.0.0.0
responded, then the 0th element of the bitarray is true. At the end I write the bitarray to a file.
Here is the code:
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
What can I do to make this run faster? Any optimisations at all, even if very small, are welcome!