我正在尝试编写一些代码,这些代码将采用“假定的”域名,并将根据RFC 1035对其进行验证。例如,它需要满足以下规则:
[a-z0-9\-]
(输入时域名将小写)google--com.com
)我搜索了各种Python模块(例如:tldextract),但无济于事。
如何验证域名是否符合RFC 1035?
答案 0 :(得分:5)
KISS:
import string
VALID_CHARS = string.lowercase + string.digits + '-.'
def is_valid_domain(domain):
if not all(char in VALID_CHARS for char in domain.lower()):
return False
if len(domain) > 253:
return False
if '--' in domain:
return False
if '..' in domain:
return False
return True
有时候聪明,但这似乎不是其中之一。
答案 1 :(得分:3)
我认为只要您只关注RFC 1035域,就可以自己解决这个问题。后来的规范允许更多种类的域名,所以这对现实世界来说还不够!
这是一个解决方案,它使用正则表达式来匹配遵循RFC第6页和第7页所述的“首选名称语法”的域名。它处理除了单个模式的字符数的顶级限制之外的所有内容:
import re
def validate_domain_name(name):
if len(name) > 255: return False
pattern = r"""(?X) # use verbose mode for this pattern
^ # match start of the input
(?: # non-capturing group for the whole name
[a-zA-Z] # first character of first label
(?: # non-capturing group for the rest of the first label
[a-zA-Z0-9\-]{,61} # match middle characters of label
[a-zA-Z0-9] # match last character of a label
)? # characters after the first are optional
(?: # non-capturing group for later labels
\. # match a dot
[a-zA-Z](?:[a-zA-Z0-9\-]{,61}[a-zA-Z0-9])? # match a label as above
)* # there can be zero or more labels after the first
)? # the whole name is optional ("" is valid)
$ # match the end of the input"""
return re.match(pattern, name) is not None # test and return a Boolean