Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python socket connection timeout

Tags:

python

sockets

I have a socket that I want to timeout when connecting so that I can cancel the whole operation if it can't connect yet it also want to use the makefile for the socket which requires no timeout.

Is there an easy way to do this or is this going to be a difficult thing to do?

Does python allow a reset of the timeout after connected so that I can use makefile and still have a timeout for the socket connection

like image 351
anonymous Avatar asked Aug 07 '10 21:08

anonymous


People also ask

What does socket timeout to Python?

Socket connection timeout High A new Python socket by default doesn't have a timeout. Its timeout defaults to None. Not setting the connection timeout parameter can result in blocking socket mode. In blocking mode, operations block until complete or the system returns an error.

How do I increase the socket timeout in Python?

The typical approach is to use select() to wait until data is available or until the timeout occurs. Only call recv() when data is actually available. To be safe, we also set the socket to non-blocking mode to guarantee that recv() will never block indefinitely.

How do I set a socket timeout?

Answer: Just set the SO_TIMEOUT on your Java Socket, as shown in the following sample code: String serverName = "localhost"; int port = 8080; // set the socket SO timeout to 10 seconds Socket socket = openSocket(serverName, port); socket. setSoTimeout(10*1000);

How do I fix timeout error in Python?

In Python, use the stdin. readline() and stdout. write() instead of input and print. Ensure that the input value to test cases is passed in the expected format.


2 Answers

You just need to use the socket settimeout() method before attempting the connect(), please note that after connecting you must settimeout(None) to set the socket into blocking mode, such is required for the makefile . Here is the code I am using:

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.settimeout(10) sock.connect(address) sock.settimeout(None) fileobj = sock.makefile('rb', 0) 
like image 81
João Pinto Avatar answered Sep 17 '22 15:09

João Pinto


If you are using Python2.6 or newer, it's convenient to use socket.create_connection

sock = socket.create_connection(address, timeout=10) sock.settimeout(None) fileobj = sock.makefile('rb', 0) 
like image 37
John La Rooy Avatar answered Sep 17 '22 15:09

John La Rooy