Files
colony/colony/utils/network.py
T
2026-09-19 20:39:12 +02:00

41 lines
1.2 KiB
Python

import ipaddress
import socket
MAX_RANGE_SIZE = 1024
def get_local_subnet():
return ipaddress.ip_network(f"{get_local_ip()}/24", strict=False)
def get_local_ip():
try:
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
s.connect(("192.0.2.1", 9))
return s.getsockname()[0]
except OSError:
pass
try:
return socket.gethostbyname(socket.gethostname())
except OSError:
return "127.0.0.1"
def get_hostname():
return socket.gethostname()
def hosts_in_range(start, end, exclude=()):
try:
first = ipaddress.IPv4Address(start)
last = ipaddress.IPv4Address(end)
except ValueError as e:
raise ValueError(f"Invalid discovery range {start!r}-{end!r}: {e}") from e
if first > last:
raise ValueError(f"Invalid discovery range: {start} is after {end}")
if int(last) - int(first) + 1 > MAX_RANGE_SIZE:
raise ValueError(f"Discovery range {start}-{end} has more than {MAX_RANGE_SIZE} addresses")
excluded = {str(host) for host in exclude}
hosts = (str(ipaddress.IPv4Address(value)) for value in range(int(first), int(last) + 1))
return [host for host in hosts if host not in excluded]