port-for: Local TCP Ports Management

1.0.0 · active · verified Thu Apr 09

Port-for is a utility that assists with local TCP ports management. It can identify an unused TCP localhost port and maintain an association with a given identifier, ensuring that subsequent requests for the same ID return the same port number. The current version is 1.0.0, primarily functioning as a local port management tool.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates finding an ephemeral available port using `available_ports` and managing persistent port assignments with `PortFor`. `PortFor` ensures that once a port is assigned to an ID, subsequent requests with the same ID return that same port.

from port_for import available_ports, PortFor

# Find an ephemeral available port (context manager ensures release)
with available_ports(5000) as port:
    print(f"Found available port (5000 or next): {port}")

# Use PortFor for persistent port assignment based on an ID
port_manager = PortFor()

# Assign a port for 'my-service' (will try 8000 first)
my_service_port = port_manager.forward_port("my-service", 8000)
print(f"Assigned port for 'my-service': {my_service_port}")

# Assign a port for 'another-service' (will try 9000 first)
another_service_port = port_manager.forward_port("another-service", 9000)
print(f"Assigned port for 'another-service': {another_service_port}")

# Subsequent calls with the same ID will return the same assigned port
same_service_port = port_manager.forward_port("my-service", 8000) # 8000 is a suggestion, not a requirement
print(f"Re-requested port for 'my-service' (should be {my_service_port}): {same_service_port}")

# To release a port (optional, happens on process exit by default)
port_manager.release("another-service")
print("Released port for 'another-service'")

view raw JSON →