Python Forum
Find a local free port to start a server in linux - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: General (https://python-forum.io/forum-1.html)
+--- Forum: Code sharing (https://python-forum.io/forum-5.html)
+--- Thread: Find a local free port to start a server in linux (/thread-13422.html)



Find a local free port to start a server in linux - Gribouillis - Oct-14-2018

The following function uses the output of ss -lntu to solve this problem
import subprocess as sp
import re
import itertools as itt

def find_free_port(start=9000):
    s = sp.check_output(['ss', '-lntu']).decode()
    maybusy = set(int(x) for x in re.findall('\d+', s))
    return next(itt.filterfalse(maybusy.__contains__, itt.count(start)))

if __name__ == '__main__':
    print('free port:', find_free_port())