Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate a hostname string

Following up to Regular expression to match hostname or IP Address? and using Restrictions on valid host names as a reference, what is the most readable, concise way to match/validate a hostname/fqdn (fully qualified domain name) in Python? I've answered with my attempt below, improvements welcome.

like image 541
kostmo Avatar asked Mar 28 '10 05:03

kostmo


People also ask

How do I check if a hostname is valid?

The HostName test performs DNS lookup and provides information about how a domain or hostname (www.yourdomain.com) is resolved to an IP address (69.147. 114.210). Common use of the HostName test is to verify that the DNS records are correct and specific domain points to the correct IP address.

How do I know if my FQDN is valid?

The validation of FQDN object is performed using RegEx pattern ^([a-zA-Z0-9. _-])+$ by the system to determine if a given hostname uses valid characters. Where ^ specifies start of a string, and $ specifies end of a string and + indicates one or more strings in the Round Brackets. [a-zA-Z0-9.

How do I check if a hostname is valid in C#?

CheckHostName(String) Method is used to determine whether the specified host name is a valid DNS name or not. Syntax: public static UriHostNameType CheckHostName (string name);

What characters are allowed in a hostname?

Valid characters for hostnames are ASCII(7) letters from a to z, the digits from 0 to 9, and the hyphen (-). A hostname may not start with a hyphen. Hostnames are often used with network client and server programs, which must generally translate the name to an address for use.


1 Answers

import re def is_valid_hostname(hostname):     if len(hostname) > 255:         return False     if hostname[-1] == ".":         hostname = hostname[:-1] # strip exactly one dot from the right, if present     allowed = re.compile("(?!-)[A-Z\d-]{1,63}(?<!-)$", re.IGNORECASE)     return all(allowed.match(x) for x in hostname.split(".")) 

ensures that each segment

  • contains at least one character and a maximum of 63 characters
  • consists only of allowed characters
  • doesn't begin or end with a hyphen.

It also avoids double negatives (not disallowed), and if hostname ends in a ., that's OK, too. It will (and should) fail if hostname ends in more than one dot.

like image 177
Tim Pietzcker Avatar answered Sep 23 '22 21:09

Tim Pietzcker