如何确定用户输入的是主机名还是IP地址?

4
用户将输入主机名或IP地址。如果用户输入的是IP地址,我希望保持不变,但如果用户输入的是主机名,我希望使用以下方法将其转换为IP地址:
def convert(hostname):
    command = subprocess.Popen(['host', hostname],
                           stdout=subprocess.PIPE).communicate()[0]

    progress1 = re.findall(r'\d+.', command)
    progress1 = ''.join(progress1)
    return progress1 

我该如何做呢?


请查看此帖子 - maverik
我已经有一个方法来验证用户输入的IP地址是否有效。 - user1881957
所以,你已经有了验证方法和转换方法,你只需要将它们结合起来,那么真正的问题是什么呢? - Samuele Mattiuzzo
在发布这个问题之前,我没有转换方法。现在,我有了这个函数socket.gethostbyname(ip4_or_hostname),但是它在我的代码中不起作用。 - user1881957
4个回答

7
获取IP地址是否为IP地址或主机名:
要判断输入是IP地址还是主机名:
ip4 = socket.gethostbyname(ip4_or_hostname)

socket.gethostbyname('555') # -> '0.0.2.43' - Sergey11g
1
@Sergey11g 2*256 + 43555。顶级域名是按字母顺序排列的。 - jfs
使用这个有什么缺点吗? - Raul Chiarella

1
你可以使用正则表达式来匹配输入并测试它是否为IP地址。
test = re.compile('\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b')
result = test.match(hostname)
if not result:
    # no match -> must be an hostname #
    convert(hostname)

那个正则表达式允许无效的IP地址(如999.999.999.999),因此您可能需要稍微调整一下,这只是一个快速示例。


请注意,它不涵盖IPv6地址。在Python3上,您可以使用https://docs.python.org/3/library/ipaddress.html。 - Jared

0

在stackoverflow上已经有很多关于验证IP地址的问题。

  1. Python中的IP地址验证
  2. Python中的IP地址验证方法

我想问一下,为什么你要与子进程通信呢?当你可以利用标准python库来完成这个任务时。

我建议使用python内置功能将主机名解析为IP地址。

你可以通过导入并使用python sockets库来实现。

例如,使用 link1 中找到的代码:

import socket
import re
regex = re.compile(r"^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$")
result = regex.match(address)
if not result:
    address = socket.gethostbyname(address)

0
在我的情况下,主机名只能包含-作为分隔符。因此,您可以根据需要取消注释并使用它。
import re

regex = "^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])$"
# string_check= re.compile('[@_!#$%^&*()<>?/\|}{~:.]')
string_check= re.compile('[-]')

ip_host_detail = {}
    
def is_valid_hostname_ip(IpHost):
    # pass regular expression and ip string into search() method
    
    if (re.search(regex, IpHost)):
        print("Valid Ip address")
        ip_host_detail['is_ip'] = 'True'
        ip_host_detail['is_hostname'] = 'False'
        return True
    elif(string_check.search(IpHost)):
        print("Contain hostname")
        ip_host_detail['is_hostname'] = 'True'
        ip_host_detail['is_ip'] = 'False'
            return True
    else:
        print("Invalid Ip address or hostname:- " + str(IpHost))
        ip_host_detail['is_hostname'] = 'False'
        ip_host_detail['is_ip'] = 'False'
        return False
    
    
IpHost = sys.argv[1]
# IpHost = 'RACDC1-VM123'

is_valid_hostname_ip(IpHost)
print(ip_host_detail)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接