Commit 90397715 by Sheng

Optimized is_valid_hostname

parent 9a49c9e5
import ipaddress import ipaddress
import re import re
try: try:
from types import UnicodeType from types import UnicodeType
except ImportError: except ImportError:
UnicodeType = str 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'): def to_str(bstr, encoding='utf-8'):
if isinstance(bstr, bytes): if isinstance(bstr, bytes):
return bstr.decode(encoding) return bstr.decode(encoding)
...@@ -43,17 +46,16 @@ def is_valid_port(port): ...@@ -43,17 +46,16 @@ def is_valid_port(port):
def is_valid_hostname(hostname): def is_valid_hostname(hostname):
if hostname[-1] == ".": if hostname[-1] == '.':
# strip exactly one dot from the right, if present # strip exactly one dot from the right, if present
hostname = hostname[:-1] hostname = hostname[:-1]
if len(hostname) > 253: if len(hostname) > 253:
return False return False
labels = hostname.split(".") labels = hostname.split('.')
# the TLD must be not all-numeric # the TLD must be not all-numeric
if re.match(r"[0-9]+$", labels[-1]): if numeric.match(labels[-1]):
return False return False
allowed = re.compile(r"(?!-)[a-z0-9-]{1,63}(?<!-)$", re.IGNORECASE)
return all(allowed.match(label) for label in labels) return all(allowed.match(label) for label in labels)
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment