I have written a rather simple port scanner using python and I would like to know things I could do better regarding:
Code quality, making the code in general better
Performance, making the code run faster and more efficient
Making the scan more lightweight for the system being scanned so there is no risk of it crashing
At the moment it takes around 160 seconds to scan all ports.
Thank you in advance.
import socket import time import threading from queue import Queue socket.setdefaulttimeout(0.25) print_lock = threading.Lock() target = '127.0.0.1' def portscan(port): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: con = s.connect((target, port)) with print_lock: print('Port', port, 'is open!') con.close() except: pass def threader(): while True: worker = q.get() portscan(worker) q.task_done() q = Queue() startTime = time.time() for x in range(100): t = threading.Thread(target=threader) t.daemon = True t.start() for worker in range(1, 65536): q.put(worker) q.join() print('Time taken:', time.time() - startTime)