Is there a timeout value for socket.gethostbyname (hostname) in python?

I translate the hostname into IPv4 address using gethostbyname() of socket in python. Sometimes it takes a little time to display the IP address. I was wondering if there is a default timeout value for each search. This is how I use a socket in my program -

 try: addr = socket.gethostbyname(hostname) except socket.gaierror: addr = "" print hostname+" : "+addr 

Just need to add one more question, is it likely that this can skip any IP address? Has anyone had any experience converting a large sample of a host name to an IP address?

+7
python sockets
source share
2 answers

Here is the whole Socket timeout file.

 import socket try: _GLOBAL_DEFAULT_TIMEOUT = socket._GLOBAL_DEFAULT_TIMEOUT except AttributeError: _GLOBAL_DEFAULT_TIMEOUT = object() 

As you can see, GLOBAL_DEFAULT_TIMEOUT = object() is just creating an empty object.

socket.setsocketimeout will set the default timeout for new sockets, however, if you do not use sockets directly, this can be easily overwritten.

See this answer for more details.

EDIT: Regarding your next question, yes. I made a program that included a host name for IP address translation, and I had problems with missing addresses. Not sure if this was due to a timeout. I just needed to double check.

+1
source share

Here is an example of using an alarm (for systems like posix) to set a timeout for socket.gethostbyname :

Installation Code:

 from contextlib import contextmanager import signal def raise_error(signum, frame): """This handler will raise an error inside gethostbyname""" raise OSError @contextmanager def set_signal(signum, handler): """Temporarily set signal""" old_handler = signal.getsignal(signum) signal.signal(signum, handler) try: yield finally: signal.signal(signum, old_handler) @contextmanager def set_alarm(time): """Temporarily set alarm""" signal.setitimer(signal.ITIMER_REAL, time) try: yield finally: signal.setitimer(signal.ITIMER_REAL, 0) # Disable alarm @contextmanager def raise_on_timeout(time): """This context manager will raise an OSError unless The with scope is exited in time.""" with set_signal(signal.SIGALRM, raise_error): with set_alarm(time): yield 

Execution code

 import socket try: with raise_on_timeout(0.1): # Timeout in 100 milliseconds print(socket.gethostbyname(socket.gethostname())) except OSError: print("Could not gethostbyname in time") 
0
source share

All Articles