Reputation:
I was making an IP scanner , that works with multi-threading.
After running threads I print returned values(a list)
But the functions are running again without returning a list.
It happens when the function is equal to a variable. That takes more time because functions run one by one.
What to do ?
def first_50IP() :
prefix = "192.168.1."
condition = "Destination host unreachable"
condition2 = "Request timed out"
list1 = []
for xxx in range(0,50) :
ip = prefix + str(xxx)
code = "ping " + ip + " -n 1 -l 1"
ping = os.popen(code).read()
#ping = subprocess.check_output(code).decode('utf-8')
if condition not in ping and condition2 not in ping:
print(G + ip)
list1.append(ip)
return list1
def second_50IP() :
prefix = "192.168.1."
condition = "Destination host unreachable"
condition2 = "Request timed out"
list2 = []
for xxx in range(50,100) :
ip = prefix + str(xxx)
code = "ping " + ip + " -n 1 -l 1"
ping = os.popen(code).read()
#ping = subprocess.check_output(code).decode('utf-8')
if condition not in ping and condition2 not in ping:
print(G + ip)
list2.append(ip)
return list2
thread1 = threading.Thread(target=first_50IP)
thread2 = threading.Thread(target=second_50IP)
thread1.start()
thread2.start()
thread1.join()
thread2.join()
print("\nResults : \n")
final_ip1 = first_50IP()
final_ip2 = second_50IP()
print(final_ip1)
print(final_ip2)
Upvotes: 1
Views: 108
Reputation: 15861
You are running the same functions twice. The first time in a dedicated thread and then in the main thread again.
Use executors and futures to avoid that:
with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
first = executor.submit(first_50IP)
second = executor.submit(second_50IP)
print("\nResults : \n")
final_ip1 = first.result()
final_ip2 = second.result()
print(final_ip1)
print(final_ip2)
A side note: you can have just one function instead of using two almost identical like this:
def ping_many(start, count) :
prefix = "192.168.1."
condition = "Destination host unreachable"
condition2 = "Request timed out"
list1 = []
for xxx in range(start, start+count) :
ip = prefix + str(xxx)
code = "ping " + ip + " -n 1 -l 1"
ping = os.popen(code).read()
#ping = subprocess.check_output(code).decode('utf-8')
if condition not in ping and condition2 not in ping:
print(G + ip)
list1.append(ip)
return list1
In this case you can submit functions with different parameters to executor like this:
tasks = {}
with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
for start in [0, 50]:
tasks.add(executor.submit(ping_many, start, 50))
print("\nResults : \n")
for task in tasks:
print(task.result())
Upvotes: 1