mirror of
https://github.com/varun-r-mallya/py-libp2p.git
synced 2025-12-31 20:36:24 +00:00
Update examples to use dynamic host IP instead of hardcoded localhost
This commit is contained in:
@ -17,9 +17,22 @@ try:
|
||||
get_wildcard_address,
|
||||
)
|
||||
except ImportError:
|
||||
# Fallbacks if utilities are missing
|
||||
# Fallbacks if utilities are missing - use minimal network discovery
|
||||
import socket
|
||||
def get_available_interfaces(port: int, protocol: str = "tcp"):
|
||||
return [Multiaddr(f"/ip4/127.0.0.1/{protocol}/{port}")]
|
||||
# Try to get local network interfaces, fallback to loopback
|
||||
addrs = []
|
||||
try:
|
||||
# Get hostname IP (better than hardcoded localhost)
|
||||
hostname = socket.gethostname()
|
||||
local_ip = socket.gethostbyname(hostname)
|
||||
if local_ip != "127.0.0.1":
|
||||
addrs.append(Multiaddr(f"/ip4/{local_ip}/{protocol}/{port}"))
|
||||
except exception:
|
||||
pass
|
||||
# Always include loopback as fallback
|
||||
addrs.append(Multiaddr(f"/ip4/127.0.0.1/{protocol}/{port}"))
|
||||
return addrs
|
||||
|
||||
def expand_wildcard_address(addr: Multiaddr, port: int | None = None):
|
||||
if port is None:
|
||||
@ -28,6 +41,12 @@ except ImportError:
|
||||
return [Multiaddr(addr_str + f"/{port}")]
|
||||
|
||||
def get_optimal_binding_address(port: int, protocol: str = "tcp"):
|
||||
# Try to get a non-loopback address first
|
||||
interfaces = get_available_interfaces(port, protocol)
|
||||
for addr in interfaces:
|
||||
if "127.0.0.1" not in str(addr):
|
||||
return addr
|
||||
# Fallback to loopback if no other interfaces found
|
||||
return Multiaddr(f"/ip4/127.0.0.1/{protocol}/{port}")
|
||||
|
||||
def get_wildcard_address(port: int, protocol: str = "tcp"):
|
||||
|
||||
Reference in New Issue
Block a user