Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/validators/hostname.py: 89%
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1"""Hostname."""
3# standard
4from functools import lru_cache
5import re
6from typing import Optional
8from .domain import domain
10# local
11from .ip_address import ipv4, ipv6
12from .utils import validator
15@lru_cache
16def _port_regex():
17 """Port validation regex."""
18 return re.compile(
19 r"^\:(6553[0-5]|655[0-2][0-9]|65[0-4][0-9]{2}|"
20 + r"6[0-4][0-9]{3}|[1-5][0-9]{4}|[1-9][0-9]{0,3})$",
21 )
24@lru_cache
25def _simple_hostname_regex():
26 """Simple hostname validation regex."""
27 # {0,59} because two characters are already matched at
28 # the beginning and at the end, making the range {1, 61}
29 return re.compile(
30 r"^(?!-)[a-z0-9](?:[a-z0-9-]{0,59}[a-z0-9])?(?<!-)$", re.IGNORECASE | re.ASCII
31 )
34def _port_validator(value: str):
35 """Returns host segment if port is valid."""
36 if value.count("]:") == 1:
37 # with ipv6
38 host_seg, port_seg = value.rsplit(":", 1)
39 if _port_regex().fullmatch(f":{port_seg}"):
40 return host_seg.lstrip("[").rstrip("]")
42 if value.count(":") == 1:
43 # with ipv4 or simple hostname
44 host_seg, port_seg = value.rsplit(":", 1)
45 if _port_regex().fullmatch(f":{port_seg}"):
46 return host_seg
48 return None
51@validator
52def hostname(
53 value: str,
54 /,
55 *,
56 skip_ipv6_addr: bool = False,
57 skip_ipv4_addr: bool = False,
58 may_have_port: bool = True,
59 maybe_simple: bool = True,
60 consider_tld: bool = False,
61 private: Optional[bool] = None, # only for ip-addresses
62 rfc_1034: bool = False,
63 rfc_2782: bool = False,
64):
65 """Return whether or not given value is a valid hostname.
67 Examples:
68 >>> hostname("ubuntu-pc:443")
69 True
70 >>> hostname("this-pc")
71 True
72 >>> hostname("xn----gtbspbbmkef.xn--p1ai:65535")
73 True
74 >>> hostname("_example.com")
75 ValidationError(func=hostname, args={'value': '_example.com'})
76 >>> hostname("123.5.77.88:31000")
77 True
78 >>> hostname("12.12.12.12")
79 True
80 >>> hostname("[::1]:22")
81 True
82 >>> hostname("dead:beef:0:0:0:0000:42:1")
83 True
84 >>> hostname("[0:0:0:0:0:ffff:1.2.3.4]:-65538")
85 ValidationError(func=hostname, args={'value': '[0:0:0:0:0:ffff:1.2.3.4]:-65538'})
86 >>> hostname("[0:&:b:c:@:e:f::]:9999")
87 ValidationError(func=hostname, args={'value': '[0:&:b:c:@:e:f::]:9999'})
89 Args:
90 value:
91 Hostname string to validate.
92 skip_ipv6_addr:
93 When hostname string cannot be an IPv6 address.
94 skip_ipv4_addr:
95 When hostname string cannot be an IPv4 address.
96 may_have_port:
97 Hostname string may contain port number.
98 maybe_simple:
99 Hostname string maybe only hyphens and alpha-numerals.
100 consider_tld:
101 Restrict domain to TLDs allowed by IANA.
102 private:
103 Embedded IP address is public if `False`, private/local if `True`.
104 rfc_1034:
105 Allow trailing dot in domain/host name.
106 Ref: [RFC 1034](https://www.rfc-editor.org/rfc/rfc1034).
107 rfc_2782:
108 Domain/Host name is of type service record.
109 Ref: [RFC 2782](https://www.rfc-editor.org/rfc/rfc2782).
111 Returns:
112 (Literal[True]): If `value` is a valid hostname.
113 (ValidationError): If `value` is an invalid hostname.
114 """
115 if not value:
116 return False
118 def _matches_simple_hostname(host: str):
119 if not maybe_simple:
120 return False
121 # A trailing dot (RFC 1034) is also valid on a simple, single-label
122 # hostname, not only on the dotted names handled by `domain()`.
123 if rfc_1034 and host.endswith("."):
124 host = host[:-1]
125 return _simple_hostname_regex().fullmatch(host)
127 if may_have_port and (host_seg := _port_validator(value)):
128 return (
129 _matches_simple_hostname(host_seg)
130 or domain(host_seg, consider_tld=consider_tld, rfc_1034=rfc_1034, rfc_2782=rfc_2782)
131 or (False if skip_ipv4_addr else ipv4(host_seg, cidr=False, private=private))
132 or (False if skip_ipv6_addr else ipv6(host_seg, cidr=False))
133 )
135 return (
136 _matches_simple_hostname(value)
137 or domain(value, consider_tld=consider_tld, rfc_1034=rfc_1034, rfc_2782=rfc_2782)
138 or (False if skip_ipv4_addr else ipv4(value, cidr=False, private=private))
139 or (False if skip_ipv6_addr else ipv6(value, cidr=False))
140 )