4

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?

At the moment this is how I'm doing it:

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

Yuck!

Cera
  • 1,879
  • 2
  • 20
  • 29

1 Answers1

12

The simplest way that I know of to check if a particular port is available is to try and bind to it or try to connect to it (if you want TCP). If the bind (or connect) succeeds, it was available (is in use).

However, if you simply want any open port, you can bind to port 0, and the opperating system will assign you a port.

David Wolever
  • 148,955
  • 89
  • 346
  • 502