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.
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.
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.
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);
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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With