我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
那么如何在上面的代码中区分这些情况呢?