Python Forum

Full Version: How does this code work?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
So I would consider myself just above a newbie. I know enough to get myself into trouble.

Anyways, I was looking into messing around with threading today and with the assistance of a youtube video built a multi-threaded port scanner. Everything works great but I am having trouble wrapping my head around some of the code. Here is the code in it's entirety:

import threading
import socket
from queue import Queue
import time

print_lock = threading.Lock()

target = input("What is the IP Address/Host you wish to scan?")
port_start = input("What is the start of the port range?")
port_end = input("What is the end of the port range?")

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()

start = time.time()

for x in range(30):
    t = threading.Thread(target=threader)
    t.daemon = True
    t.start()

for worker in range(int(port_start), int(port_end)):
    q.put(worker)

q.join()

print('Entire operation took ', time.time()-start, ' seconds.')
So, my confusion centers around the two for loops. Logically, I would think that the 'for worker' loop would need to occur first because that is the one that puts data into the queue. However, that doesn't seem to be the case, the program runs just fine the way it is. Can someone explain what I am missing here?
I would suggest watching this video: https://www.youtube.com/watch?v=MCs5OvhV9S4
(code here): https://github.com/dabeaz/concurrencylive
Even though this video is three years old, it explains threading (concurrency) very well.
If that sparks your interest, you may want to watch the latest: https://www.youtube.com/watch?v=U66KuyD3...e=youtu.be
Don't watch the second without first watching the first, as the new video is on advanced features that are not yet part of python, but I expect will be soon.