验证主机名字符串 [英] Validate a hostname string

查看:119
本文介绍了验证主机名字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最多遵循>正则表达式以匹配主机名或IP地址吗? 并使用对有效主机名的限制作为参考,哪种方法最易读,最简洁在Python中匹配/验证主机名/fqdn(完全限定域名)?我在下面的尝试中已经回答过,欢迎进行改进.

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.

推荐答案

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("."))

确保每个细分

  • 至少包含一个字符,最多63个字符
  • 仅包含允许的字符
  • 不以连字符开头或结尾.

它还避免了双负数(not disallowed),并且如果hostname.结尾,也可以.如果hostname以多个点结束,它将(并且应该)失败.

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.

这篇关于验证主机名字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆