How can I validate that a domain name conforms to RFC 1035 using Python?

坚强是说给别人听的谎言 提交于 2019-12-04 02:47:45

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

There are times for cleverness, but this doesn't seem to be one of them.

I think it's pretty simple to solve this for yourself, as long as you're only concerned with RFC 1035 domains. Later specifications allow more kinds of domain names, so this will not be enough for the real world!

Here's a solution that uses a regex to match domain names that follow the "preferred name syntax" described on pages 6 and 7 of the RFC. It handles the everything but the top level limit on the number of characters with a single pattern:

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
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!