Python Forum
Find a local free port to start a server in linux
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Find a local free port to start a server in linux
#1
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())
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020