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:


  • 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