1 """Network utilities."""
3 from __future__
import annotations
5 from ipaddress
import IPv4Address, IPv6Address, ip_address, ip_network
11 IPV6_IPV4_LOOPBACK = ip_network(
"::ffff:127.0.0.0/104")
14 ip_network(
"127.0.0.0/8"),
15 ip_network(
"::1/128"),
21 ip_network(
"10.0.0.0/8"),
22 ip_network(
"172.16.0.0/12"),
23 ip_network(
"192.168.0.0/16"),
24 ip_network(
"fd00::/8"),
25 ip_network(
"::ffff:10.0.0.0/104"),
26 ip_network(
"::ffff:172.16.0.0/108"),
27 ip_network(
"::ffff:192.168.0.0/112"),
31 LINK_LOCAL_NETWORKS = (
32 ip_network(
"169.254.0.0/16"),
33 ip_network(
"fe80::/10"),
34 ip_network(
"::ffff:169.254.0.0/112"),
39 """Check if an address is a loopback address."""
40 return address.is_loopback
or address
in IPV6_IPV4_LOOPBACK
43 def is_private(address: IPv4Address | IPv6Address) -> bool:
44 """Check if an address is a unique local non-loopback address."""
45 return any(address
in network
for network
in PRIVATE_NETWORKS)
49 """Check if an address is link-local (local but not necessarily unique)."""
50 return address.is_link_local
53 def is_local(address: IPv4Address | IPv6Address) -> bool:
54 """Check if an address is on a local network."""
58 def is_invalid(address: IPv4Address | IPv6Address) -> bool:
59 """Check if an address is invalid."""
60 return address.is_unspecified
64 """Check if a given string is an IP address."""
74 """Check if a given string is an IPv4 address."""
84 """Check if a given string is an IPv6 address."""
94 """Check if a given string is an IP address or valid hostname."""
99 if re.match(
r"^[0-9\.]+$", host):
101 if host.endswith(
"."):
103 allowed = re.compile(
r"(?!-)[A-Z\d\-]{1,63}(?<!-)$", re.IGNORECASE)
104 return all(allowed.match(x)
for x
in host.split(
"."))
108 """Normalize a given URL."""
109 url = yarl.URL(address.rstrip(
"/"))
110 if url.is_absolute()
and url.is_default_port():
111 return str(url.with_port(
None))
bool is_loopback(IPv4Address|IPv6Address address)
bool is_host_valid(str host)
bool is_private(IPv4Address|IPv6Address address)
str normalize_url(str address)
bool is_ipv6_address(str address)
bool is_link_local(IPv4Address|IPv6Address address)
bool is_ip_address(str address)
bool is_local(IPv4Address|IPv6Address address)
bool is_ipv4_address(str address)
bool is_invalid(IPv4Address|IPv6Address address)