refactor(app): 804 refactored find_free_port() in address_validation.py

This commit is contained in:
yashksaini-coder
2025-08-24 23:28:02 +05:30
parent 75ffb791ac
commit ed91ee0c31
3 changed files with 14 additions and 16 deletions

View File

@ -1,5 +1,7 @@
from __future__ import annotations
import socket
from multiaddr import Multiaddr
try:
@ -35,6 +37,13 @@ def _safe_get_network_addrs(ip_version: int) -> list[str]:
return []
def find_free_port() -> int:
"""Find a free port on localhost."""
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind(("", 0)) # Bind to a free port provided by the OS
return s.getsockname()[1]
def _safe_expand(addr: Multiaddr, port: int | None = None) -> list[Multiaddr]:
"""
Internal safe expansion wrapper. Returns a list of Multiaddr objects.
@ -147,4 +156,5 @@ __all__ = [
"get_available_interfaces",
"get_optimal_binding_address",
"expand_wildcard_address",
"find_free_port",
]