title: Scan every possible port in a host using Python
body: <p>I'm writing a program which needs to scan all 65535 ports in a host searching for the ones which are open. This is what I have so far, and it works, but <strong>it produces different results every time I execute the script</strong>, why is this happening?</p>
  
  <pre><code>def check_open_port(host, port):
      s = socket.socket()
      s.settimeout(0.1)
      # the SO_REUSEADDR flag tells the kernel to reuse a local 
      # socket in TIME_WAIT state, without waiting for its natural
      # timeout to expire.
      s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  
      try:
          code = s.connect_ex((host, port))
          s.close()
  
          if code == 0:
              return True
          else:
              return False
      except socket.error:
          return False
  
  
  def get_open_ports(host, max_port=65535):
      open_ports = []
  
      def worker(port):
          if check_open_port(host, port):
              open_ports.append(port)
  
  
      pool = ThreadPoolExecutor(max_workers=10000)
      [pool.submit(worker, port) for port in range(1, max_port + 1)]
      pool.shutdown(wait=True)
  
      return open_ports
  </code></pre>
  
  <p>For example, in a host with ports 22, 80, and 443 open, sometimes I get this response:</p>
  
  <p><code>[22, 80]</code></p>
  
  <p>and sometimes I get:</p>
  
  <p><code>[22, 80, 443]</code></p>
  
  <p>or even:</p>
  
  <p><code>[22]</code></p>
  
  <p>Hosts with more open ports produce more combinations.</p>
  
  <p>I have played with <code>max_workers</code> and <code>settimeout()</code> values, but I can't get it to work well. The only time it worked was without using threads, but obviously it took ages to complete, I need to use them.</p>
  
  <p>Am I missing something? Is there another way to implement this?</p>