Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 11 additions & 2 deletions src/validators/hostname.py
Original file line number Diff line number Diff line change
Expand Up @@ -113,16 +113,25 @@ def hostname(
if not value:
return False

def _matches_simple_hostname(host: str):
if not maybe_simple:
return False
# A trailing dot (RFC 1034) is also valid on a simple, single-label
# hostname, not only on the dotted names handled by `domain()`.
if rfc_1034 and host.endswith("."):
host = host[:-1]
return _simple_hostname_regex().match(host)

if may_have_port and (host_seg := _port_validator(value)):
return (
(_simple_hostname_regex().match(host_seg) if maybe_simple else False)
_matches_simple_hostname(host_seg)
or domain(host_seg, consider_tld=consider_tld, rfc_1034=rfc_1034, rfc_2782=rfc_2782)
or (False if skip_ipv4_addr else ipv4(host_seg, cidr=False, private=private))
or (False if skip_ipv6_addr else ipv6(host_seg, cidr=False))
)

return (
(_simple_hostname_regex().match(value) if maybe_simple else False)
_matches_simple_hostname(value)
or domain(value, consider_tld=consider_tld, rfc_1034=rfc_1034, rfc_2782=rfc_2782)
or (False if skip_ipv4_addr else ipv4(value, cidr=False, private=private))
or (False if skip_ipv6_addr else ipv6(value, cidr=False))
Expand Down
5 changes: 5 additions & 0 deletions tests/test_hostname.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@
("this-pc", False, False),
("lab-01a-notebook:404", False, False),
("4-oh-4", False, False),
# simple, single-label hostname w/ trailing dot (RFC 1034); see #442
("this-pc.", True, False),
("ie.", True, False),
# hostname w/ optional ports
("example.com:4444", False, False),
("kräuter.com.", True, False),
Expand Down Expand Up @@ -45,6 +48,8 @@ def test_returns_true_on_valid_hostname(value: str, rfc_1034: bool, rfc_2782: bo
("this-pc-is-sh*t", False, False),
("lab-01a-note._com_.com:404", False, False),
("4-oh-4:@.com", False, False),
# trailing dot is only allowed with rfc_1034; see #442
("this-pc.", False, False),
# bad (hostname w/ optional ports)
("example.com:-4444", False, False),
("xn----gtbspbbmkef.xn--p1ai:65538", False, False),
Expand Down