Skip to content

Instantly share code, notes, and snippets.

@gabrielfalcao
Created October 31, 2015 18:30
Show Gist options
  • Save gabrielfalcao/20e567e188f588b65ba2 to your computer and use it in GitHub Desktop.
Save gabrielfalcao/20e567e188f588b65ba2 to your computer and use it in GitHub Desktop.
Getting a random free tcp port in python using sockets
# Getting a random free tcp port in python using sockets
def get_free_tcp_port():
tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
tcp.bind(('', 0))
addr, port = tcp.getsockname()
tcp.close()
return port
def get_free_tcp_address():
tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
tcp.bind(('', 0))
host, port = tcp.getsockname()
tcp.close()
return 'tcp://{host}:{port}'.format(**locals())
@s3rgeym
Copy link

s3rgeym commented Mar 4, 2024

more modern and pythonic:

import socket
from contextlib import closing


def get_local_ip() -> str:
    with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as s:
        s.connect(("8.8.8.8", 53))
        return s.getsockname()[0]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment