@@ -26,6 +26,21 @@ def _simple_hostname_regex():
26
26
return re .compile (r"^[a-zA-Z0-9][a-zA-Z0-9-]{0,61}[a-zA-Z0-9]$" )
27
27
28
28
29
+ def _port_validator (value : str ):
30
+ """Returns host segment if port is valid."""
31
+ if value .count ("]:" ) == 1 :
32
+ # with ipv6
33
+ host_seg , port_seg = value .rsplit (":" , 1 )
34
+ if _port_regex ().match (f":{ port_seg } " ):
35
+ return host_seg .lstrip ("[" ).rstrip ("]" )
36
+
37
+ if value .count (":" ) == 1 :
38
+ # with ipv4 or simple hostname
39
+ host_seg , port_seg = value .rsplit (":" , 1 )
40
+ if _port_regex ().match (f":{ port_seg } " ):
41
+ return host_seg
42
+
43
+
29
44
@validator
30
45
def hostname (
31
46
value : str ,
@@ -85,19 +100,13 @@ def hostname(
85
100
86
101
> *New in version 0.21.0*.
87
102
"""
88
- if may_have_port :
89
- if value .count ("]:" ) == 1 and not skip_ip_addr :
90
- host_seg , port_seg = value .rsplit (":" , 1 )
91
- return _port_regex ().match (f":{ port_seg } " ) and ipv6 (
92
- host_seg .lstrip ("[" ).rstrip ("]" ), cidr = False
93
- )
94
- if value .count (":" ) == 1 :
95
- host_seg , port_seg = value .rsplit (":" , 1 )
96
- return _port_regex ().match (f":{ port_seg } " ) and (
97
- (_simple_hostname_regex ().match (host_seg ) if maybe_simple else False )
98
- or domain (host_seg , rfc_1034 = rfc_1034 , rfc_2782 = rfc_2782 )
99
- or (False if skip_ip_addr else ipv4 (host_seg , cidr = False ))
100
- )
103
+ if may_have_port and (host_seg := _port_validator (value )):
104
+ return (
105
+ (_simple_hostname_regex ().match (host_seg ) if maybe_simple else False )
106
+ or domain (host_seg , rfc_1034 = rfc_1034 , rfc_2782 = rfc_2782 )
107
+ or (False if skip_ip_addr else ipv4 (host_seg , cidr = False ))
108
+ or (False if skip_ip_addr else ipv6 (host_seg , cidr = False ))
109
+ )
101
110
102
111
return (
103
112
(_simple_hostname_regex ().match (value ) if maybe_simple else False )
0 commit comments