Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

rfc1035

I'm trying to write some code that will take in a "supposed" domain name and will validate it according to RFC 1035. For instance, it would need to satisfy these rules:

  • Domain consists of no more than 253 total characters
  • Domain character set is [a-z0-9\-] only (will lower case the domain on input)
  • Domain cannot contain two consecutive dashes (eg: google--com.com)
  • There is a maximum subdomain limit of 127

I have searched for various Python modules (eg: tldextract) but to no avail.

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

like image 870
gleb1783 Avatar asked Jan 06 '14 16:01

gleb1783


2 Answers

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.

like image 154
Kirk Strauser Avatar answered Sep 29 '22 13:09

Kirk Strauser


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
like image 24
Blckknght Avatar answered Sep 29 '22 12:09

Blckknght