Welcome to Python Multi-Threaded Port Scanner with tkinter tutorial series Part 3. In the previous part we have discussed about ports and developed the simple port scanner program. What i think is that you experienced that the port scanning is damn slow.
No one likes to sit and wait for the response from the server. Everyone wants it to be completed within mean time. Hence, Threading module can speed up the port scanner for us. All we are required to import the threading module, which is inbuilt in Python package. Here, we will use thread locking concept to avoid multiple modification at a time.
thread_lock = threading.Lock()
threading.Lock() will allow single thread to access the variable at a time. Hence, no double modification occurs.
def threader(): while True: worker = q.get() #Fetch the port from the eorker for loop p_scan(worker) #Calls the portscan method #and pass the port number q.task_done() #Called when task is completed q = Queue() #It will create the queue and the threader for p in range(50): #It defines the number of threads to run t = threading.Thread(target=threader) t.daemon = True #This is consider thread as daemon, #so if the main thread dies it will also die t.start() #start the tread for worker in range(1,100): q.put(worker) #this is the port number to be scanned #from 1 to 100 q.join() #It waits untill the thread terminates
Here, we have defined one threader function that will fetch the work (port) from the worker for loop. Then the portscan method is called to connect to the port and print the result. The port number is passed as parameter. Once the task is completed the q.task_done() method is called.
This is how the threading speed up the port scanning. In the next tutorial we will see the basics of tkinter that we are going to use in our port scanner for GUI. Keep sharing. Stay tuned to Tech Tunes.
Follow me on Twitter