title: Multithreaded Port Scanner
body: <p>Yes, yes I know I could just use nmap but I want to try this out myself.</p>
  
  <p>I'm trying to write a threaded script to find open ports on a target IP address. This is what I have right now:</p>
  
  <pre><code>import socket, Queue
  from threading import Thread
  
  
  print "Target to scan: "
  targetIP = raw_input("&gt; ")
  print "Number of threads: "
  threads = int(raw_input("&gt; "))
  
  
  q = Queue.Queue()
  
  # Fill queue with port numbers
  for port in range(1, 1025):
      q.put(port)
  
  
  def scan(targetIP, port):
      try:
          s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
          s.settimeout(4)
          result = s.connect_ex((targetIP, port))
          if result == 0:
              print 'Port {0} is open'.format(port)
          s.close
          q.task_done()
  
  
  
  while q.full:
      for i in range(threads):
          port = q.get()
          t = Thread(target=scan, args =(targetIP, port))
          t.daemon = True
          t.start()
  </code></pre>
  
  <p>However I have a few issues:</p>
  
  <p>1) When I run this as is, it will iterate through the port queue but then just hang, never breaking from the <code>while</code> loop even though the queue empties.</p>
  
  <p>2) If I add a print line to <code>scan</code> to see whats happening, basically add a "Scanning port X" line in the beginning and a <code>print result</code> line at the end, stdout gets flooded with the "Scanning port" line for all ports in the queue, and THEN the result lines get printed. Meaning, it looks like currently the script is not waiting for <code>result</code> to get a value, and just continue iterating on as if it had. </p>
  
  <p>What am I doing wrong here?</p>