title: How do I find an open port in Linux?
body: <p>Is there some kind of system call that will return whether a port is available? Or at least a conventional way to do it that doesn't make your process a bad citizen?</p>
  
  <p>At the moment this is how I'm doing it:</p>
  
  <pre><code>def find_open_port(min_port, max_port):
      s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
      for port in range(min_port, max_port):
          if port &gt; max_port:
              raise IOError('Could not find a free port between {0} and {1}'.format(min_port, max_port))
          try:
              s.bind(('localhost', port))
              return port
          except socket.error as error:
              if error.strerror == 'Address already in use':
                  continue
              else:
                  raise error
  </code></pre>
  
  <p>Yuck!</p>