minor changes

This commit is contained in:
Maximilian Hils 2017-02-21 13:00:04 +01:00 committed by GitHub
parent 11134b669e
commit aa6b0f299e

View File

@ -1,5 +1,5 @@
import ipaddress
import re import re
from ipaddress import ip_address
# Allow underscore in host name # Allow underscore in host name
_label_valid = re.compile(b"(?!-)[A-Z\d\-_]{1,63}(?<!-)$", re.IGNORECASE) _label_valid = re.compile(b"(?!-)[A-Z\d\-_]{1,63}(?<!-)$", re.IGNORECASE)
@ -7,20 +7,23 @@ _label_valid = re.compile(b"(?!-)[A-Z\d\-_]{1,63}(?<!-)$", re.IGNORECASE)
def is_valid_host(host: bytes) -> bool: def is_valid_host(host: bytes) -> bool:
""" """
Checks if a hostname is valid. Checks if the passed bytes are a valid DNS hostname or an IPv4/IPv6 address.
""" """
try: try:
host.decode("idna") host.decode("idna")
except ValueError: except ValueError:
return False return False
# RFC1035: 255 bytes or less.
if len(host) > 255: if len(host) > 255:
return False return False
if host and host[-1:] == b".": if host and host[-1:] == b".":
host = host[:-1] host = host[:-1]
# DNS hostname
if all(_label_valid.match(x) for x in host.split(b".")): if all(_label_valid.match(x) for x in host.split(b".")):
return True return True
# IPv4/IPv6 address
try: try:
ip_address(host.decode('idna')) ipaddress.ip_address(host.decode('idna'))
return True return True
except ValueError: except ValueError:
return False return False