MCPcopy Index your code
hub / github.com/mitmproxy/mitmproxy / is_valid_host

Function is_valid_host

mitmproxy/net/check.py:11–39  ·  view source on GitHub ↗

Checks if the passed bytes are a valid DNS hostname or an IPv4/IPv6 address.

(host: AnyStr)

Source from the content-addressed store, hash-verified

9
10
11def is_valid_host(host: AnyStr) -> bool:
12 """
13 Checks if the passed bytes are a valid DNS hostname or an IPv4/IPv6 address.
14 """
15 if isinstance(host, str):
16 try:
17 host_bytes = host.encode("idna")
18 except UnicodeError:
19 return False
20 else:
21 host_bytes = host
22 try:
23 host_bytes.decode("idna")
24 except ValueError:
25 return False
26 # RFC1035: 255 bytes or less.
27 if len(host_bytes) > 255:
28 return False
29 if host_bytes and host_bytes.endswith(b"."):
30 host_bytes = host_bytes[:-1]
31 # DNS hostname
32 if all(_label_valid.match(x) for x in host_bytes.split(b".")):
33 return True
34 # IPv4/IPv6 address
35 try:
36 ipaddress.ip_address(host_bytes.decode("idna"))
37 return True
38 except ValueError:
39 return False
40
41
42def is_valid_port(port: int) -> bool:

Callers 1

parse_authorityFunction · 0.90

Calls 5

ip_addressMethod · 0.80
encodeMethod · 0.45
decodeMethod · 0.45
matchMethod · 0.45
splitMethod · 0.45

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…