Optimized is_valid_hostname

pull/26/head
Sheng 2018-08-21 21:55:57 +08:00
parent 9a49c9e5a3
commit 90397715dc
1 changed files with 7 additions and 5 deletions

View File

@ -1,13 +1,16 @@
import ipaddress
import re
try:
from types import UnicodeType
except ImportError:
UnicodeType = str
numeric = re.compile(r'[0-9]+$')
allowed = re.compile(r'(?!-)[a-z0-9-]{1,63}(?<!-)$', re.IGNORECASE)
def to_str(bstr, encoding='utf-8'):
if isinstance(bstr, bytes):
return bstr.decode(encoding)
@ -43,17 +46,16 @@ def is_valid_port(port):
def is_valid_hostname(hostname):
if hostname[-1] == ".":
if hostname[-1] == '.':
# strip exactly one dot from the right, if present
hostname = hostname[:-1]
if len(hostname) > 253:
return False
labels = hostname.split(".")
labels = hostname.split('.')
# the TLD must be not all-numeric
if re.match(r"[0-9]+$", labels[-1]):
if numeric.match(labels[-1]):
return False
allowed = re.compile(r"(?!-)[a-z0-9-]{1,63}(?<!-)$", re.IGNORECASE)
return all(allowed.match(label) for label in labels)