如何使用Python验证域名是否符合RFC 1035?

时间:2014-01-06 16:40:17

标签: python rfc1035

我正在尝试编写一些代码,这些代码将采用“假定的”域名,并将根据RFC 1035对其进行验证。例如,它需要满足以下规则:

  • 域名不超过253个字符
  • 域名字符集仅为[a-z0-9\-](输入时域名将小写)
  • 域名不能包含两个连续破折号(例如:google--com.com
  • 最大子域名限制为127

我搜索了各种Python模块(例如:tldextract),但无济于事。

如何验证域名是否符合RFC 1035?

2 个答案:

答案 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