[英]Distinguish between an IP address and FQDN
Do you know if there is any pattern/logic that could be used to distinguish between an IP address and an FQDN in python?您是否知道是否有任何模式/逻辑可用于区分 IP 地址和 python 中的 FQDN? I have a script that process user input which could be ip or fqdn and i would like to to ip validation checks if ip, and no validation check in case it is fqdn.
我有一个处理用户输入的脚本,它可能是 ip 或 fqdn,我想 ip 验证检查 ip 是否为 fqdn。
addy = "1.2.3.4"
a = addy.split('.')
match = re.search('^(([0-9]|[0-9][0-9]|[0-9][0-9][0-9]))$', a[0])
if match is not None:
if is_valid_ipv4(addy) == True:
# code continues
what is case addy is fqdn?什么是 case addy 是 fqdn? I wish to call is_valid_ipv4 if input string is only an IP address.
如果输入字符串只是 IP 地址,我希望调用 is_valid_ipv4。 Do I need a pattern for FQDN?
我需要 FQDN 的模式吗? How to distinguish between IP and FQDN?
如何区分 IP 和 FQDN?
Python knows about IP addresses. Python 知道 IP 地址。 Meanwhile, this answer gives a pretty good regexp for validating FQDNs.
同时,这个答案为验证 FQDN 提供了一个很好的正则表达式。
import ipaddress
import re
addy = "192.0.2.1"
fqdn_re = re.compile('(?=^.{4,253}$)(^((?!-)[a-zA-Z0-9-]{1,63}(?<!-)\.)+[a-zA-Z]{2,63}\.?$)')
try:
ip_addy = ipaddress.ip_address(addy)
if ip_addy.version == 4:
print("IPv4 address")
elif ip_addy.version == 6:
print("IPv6 address")
except ValueError:
if fqdn_re.search(addy):
print("FQDN address")
else:
print("Invalid address")
Personally, I'd use regex .就个人而言,我会使用 regex 。 In Python you can use the
re
package.在 Python 中,您可以使用
re
package。
Write a pattern for each (IP and FQDN) and see which gets a match ( re.match()
).为每个(IP 和 FQDN)编写一个模式,看看哪个得到匹配(
re.match()
)。
Here are some useful links:以下是一些有用的链接:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.