我在python3中使用python3将IP解析为主机名。
我需要区分三种情况:
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
那么,如何区分上述代码中的这些情况呢?
发布于 2019-11-13 09:53:55
socket.herror是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')
https://stackoverflow.com/questions/58830397
复制相似问题