DEV Community

Cover image for Python Find Available Port
Waylon Walker
Waylon Walker

Posted on • Originally published at waylonwalker.com

Python Find Available Port

When running a python process that requires a port it's handy if there is an option for it to just run on the next avaialble port. To do this we can use the socket module to determine if the port is in use or not before starting our process.

import socket

def find_port(port=8000):
    """Find a port not in ues starting at given port"""
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
        if s.connect_ex(("localhost", port)) == 0:
            return find_port(port=port + 1)
        else:
            return port
Enter fullscreen mode Exit fullscreen mode

The til series is intentionally short thoughts that come to me thoughout the day, and I get them to paper as quick as I can. You can see all the tils or full posts on my website.

Discussion (0)