0

socket.gethostbyaddr()在 python3 中使用将 IP 解析为主机名。

我需要区分3种情况:

1) success (IP resolved to hostname)
2) IP address has no DNS record
3) DNS server is temporarily unavailable

我正在使用简单的功能:

def host_lookup(addr):
    try:
        return socket.gethostbyaddr(addr)[0]
    except socket.herror:
        return None

然后我想从我的主代码中调用这个函数:

res = host_lookup('45.82.153.76')

if "case 1":
    print('success')
else if "case 2":
    print('IP address has no DNS record')
else if "case 3":
    DNS server is temporarily unavailable
else:
    print('unknown error')

socket.gethostbyaddr()当我在 python 控制台中尝试时,在每种情况下都会得到不同的错误代码:

>>> socket.gethostbyaddr('45.82.153.76')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
socket.herror: [Errno 1] Unknown host

当我故意使 DNS 无法访问时:

>>> socket.gethostbyaddr('45.82.153.76')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
socket.herror: [Errno 2] Host name lookup failure

那么如何在上面的代码中区分这些情况呢?

4

1 回答 1

0

socket.herrorOSError的子类,提供对数字错误代码的访问errno

import socket

def host_lookup(addr):
    return socket.gethostbyaddr(addr)[0]

try:
    res = host_lookup("45.82.153.76")
    print('Success: {}'.format(res))
except socket.herror as e:
    if e.errno == 1:
        print('IP address has no DNS record')
    elif e.errno == 2:
        print('DNS server is temporarily unavailable')
    else:
        print('Unknown error')
于 2019-11-13T09:53:55.837 回答