How to find open port in Linux?

Is there some kind of system call that will return an available port? Or at least the usual way to do this, which does not make your process a bad citizen?

At the moment I am doing this:

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 

Ugh!

+4
source share
1 answer

The easiest way I know to check if a particular port is available is to try connecting it or trying to connect to it (if you want to use TCP). If the binding (or connection) succeeds, it was available (used).

However, if you just want to open any open port, you can bind it to port 0, and the operating system will assign you a port.

+12
source

Source: https://habr.com/ru/post/1396341/


All Articles