Reputation: 189626
socket.gethostbyname()
works great when its argument is a real hostname. But when it's a nonexistent host, I get a 3 second timeout followed by
socket.gaierror: [Errno 11001] getaddrinfo failed
I don't mind the exception (it's appropriate), but is there any way to reduce the timeout?
Upvotes: 6
Views: 3967
Reputation: 191
I'm quite new to threading but I tried implementing @Andriy Tylychko's suggestion of using threads.
from threading import Thread
import time
def is_ip_connected(IP, timeout=2):
ans = {"success": False}
def _is_ip_connected(IP, ans):
try:
socket.gethostbyaddr(IP)
ans["success"] = True
except:
pass
time_thread = Thread(target=time.sleep, args=(timeout,))
IP_thread = Thread(target=_is_ip_connected, kwargs={"IP": IP, "ans": ans})
time_thread.start()
IP_thread.start()
while time_thread.is_alive() and IP_thread.is_alive():
pass
return(ans["success"])
print(is_ip_connected(IP="192.168.1.202"))
Upvotes: 0
Reputation: 37
A simple solution after going through this would be:
import socket
socket.setdefaulttimeout(5) #Default this is 30
socket.gethostbyname(your_url)
Upvotes: 3
Reputation: 16256
This can be impossible if Python uses system gethostbyname()
. I'm not sure you really want this because you can receive false timeouts.
Once I had a similar problem, but from C++: I had to call the function for large number of names, so long timeout was a real pain. A solution was to call it from many threads in parallel, so while some of them was stuck waiting for timeout, all others were proceeding fine.
Upvotes: 1