Allow raw ip addresses

This commit is contained in:
2026-08-20 09:32:04 +02:00
parent 0fed855cf7
commit 86e644410b
5 changed files with 82 additions and 15 deletions
+30
View File
@@ -9,6 +9,7 @@ server given for that specific endpoint.
from __future__ import annotations
import contextlib
import ipaddress
import socket
import threading
@@ -20,6 +21,35 @@ import dns.resolver
_patch_lock = threading.Lock()
def is_ip_literal(host: str) -> bool:
"""Return True if `host` is already a literal IPv4 or IPv6 address.
Such hosts have nothing to resolve — dnspython does not special-case
them, it will happily send a DNS query for e.g. "192.168.0.2" as if it
were a hostname and get NXDOMAIN back. Callers should skip resolution
entirely for these.
"""
try:
ipaddress.ip_address(host)
return True
except ValueError:
return False
def format_host_for_url(host: str) -> str:
"""Format `host` for embedding directly in a URL.
IPv6 literals need brackets (e.g. "::1" -> "[::1]"); everything else
(hostnames, IPv4 literals) is returned unchanged.
"""
try:
if ipaddress.ip_address(host).version == 6:
return f"[{host}]"
except ValueError:
pass
return host
def resolve(host: str, dns_server: str, timeout: float) -> str:
"""Resolve `host` to an IPv4 address using *only* `dns_server`.