您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

python:检查主机名是否已解析

python:检查主机名是否已解析

您可以socket.gethostbyname()为此使用:

>>> import socket
>>> socket.gethostbyname('google.com')
'74.125.224.198'
>>> socket.gethostbyname('foo')           # no host 'foo' exists on the network
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
socket.gaierror: [Errno 8] nodename nor servname provided, or not kNown

您的函数可能如下所示:

def hostname_resolves(hostname):
    try:
        socket.gethostbyname(hostname)
        return 1
    except socket.error:
        return 0

例:

>>> hostname_resolves('google.com')
1
>>> hostname_resolves('foo')
0
python 2022/1/1 18:31:46 有187人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶