python3:socket.gethostbyaddr():"Unknown host" 对比 "Host name lookup failure"

python3: socket.gethostbyaddr(): "Unknown host" vs "Host name lookup failure"

我在 python3 中使用 socket.gethostbyaddr() 将 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')

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

>>> 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

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

socket.herror is a subclass of OSError 提供对数字错误代码 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')