简体   繁体   English

在Python中确定主机是域名还是IP

[英]Determine if Host is Domain Name or IP in Python

Is there a function in Python that determines if a hostname is a domain name or an IP(v4) address? Python中是否有一个函数可以确定主机名是域名还是IP(v4)地址?

Note, the domain name may look like: alex.foo.bar.com or even (I think this is valid): 1.2.3.com .请注意,域名可能类似于: alex.foo.bar.com甚至(我认为这是有效的): 1.2.3.com

One of the visual differences between IP and domain address is when you delete dots in the IP address the result would be a number. IP 和域地址之间的视觉差异之一是,当您删除 IP 地址中的点时,结果将是一个数字。 So based on this difference we can check if the input string is an IP or a domain address.因此,基于这种差异,我们可以检查输入的字符串是 IP 还是域地址。 We remove dots in the input string and after that check if we can convert the result to an integer or we get an exception.我们删除输入字符串中的点,然后检查是否可以将结果转换为整数,否则会出现异常。

def is_ip(address):
    return address.replace('.', '').isnumeric()

Although in some IP-Representations like dotted hexadecimal (eg 0xC0.0x00.0x02.0xEB ) there can be both letters and numbers in the IP-Address.尽管在某些 IP 表示中,例如点分十六进制(例如0xC0.0x00.0x02.0xEB ),IP 地址中可以同时包含字母和数字。 However the top-level-domain (.org, .com, ...) never includes numbers.然而,顶级域(.org、.com、...)从不包含数字。 Using the function below will work in even more cases than the function above.使用下面的函数将在比上面的函数更多的情况下工作。

def is_ip(address):
    return not address.split('.')[-1].isalpha()

I'd use IPy to test if the string is an IP address, and if it isn't - assume it's a domain name.我会使用 IPy 来测试字符串是否是 IP 地址,如果不是 - 假设它是一个域名。 Eg:例如:

from IPy import IP
def isIP(str):
    try:
        IP(str)
    except ValueError:
        return False
    return True

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM