python: 检查是否为IP或DNS

7 投票
4 回答
11449 浏览
提问于 2025-04-16 14:35

怎么在Python中检查一个变量是包含DNS名称还是IP地址呢?

4 个回答

2

我建议你看看这个StackOverflow上的问题答案:

用正则表达式匹配DNS主机名或IP地址?

重点是把这两个正则表达式用“或”连接起来,这样就能得到想要的结果。

12

这个可以用。

import socket
host = "localhost"
if socket.gethostbyname(host) == host:
    print "It's an IP"
else:
    print "It's a host name"
8

你可以使用Python的re模块来检查一个变量的内容是否是一个IP地址。

下面是一个检查IP地址的例子:

import re

my_ip = "192.168.1.1"
is_valid = re.match("^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$", my_ip)

if is_valid:
    print "%s is a valid ip address" % my_ip

下面是一个检查主机名的例子:

import re

my_hostname = "testhostname"
is_valid = re.match("^(([a-zA-Z]|[a-zA-Z][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z]|[A-Za-z][A-Za-z0-9\-]*[A-Za-z0-9])$", my_hostname)

if is_valid:
    print "%s is a valid hostname" % my_hostname

撰写回答