I want to get any random open TCP port on localhost in Python. What is the easiest way?
The ephemeral ports basically lie in range 49152 - 65535. if you want to check ports in bigger range then just change the values in randint.
import pustil
from random import randint
def getfreeport():
port = randint(49152,65535)
portsinuse=[]
while True:
conns = pstuil.net_connections()
for conn in conns:
portsinuse.append(con.laddr[1])
if port in portsinuse:
port = randint(49152,65535)
else:
break
return port