python3:socket.gethostbyaddr():“未知主机” vs“主机名查找失败”

时间:2019-11-13 04:35:56

标签: python-3.x dns gethostbyaddr

我正在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

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

1 个答案:

答案 0 :(得分: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')