Get random available port with Python

Find a random available local port with this Python snippet.

#!/usr/bin/env python
from socket import socket

with socket() as s:
    s.bind(('',0))
    print(s.getsockname()[1])

Notes

  • from shell, returns on STDOUT a free port number.
  • there is a slight race condition where between end of this program and start of your shell program, another program could grab this port.

  • reference

Categories:

Updated:

Leave a Comment