Python socket connection timeout

PythonSockets

Python Problem Overview


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

Python Solutions


Solution 1 - Python

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)

Solution 2 - Python

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)

Solution 3 - Python

For setting the Socket timeout, you need to follow these steps:

import socket
socks = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socks.settimeout(10.0) # settimeout is the attr of socks.

Solution 4 - Python

Try this code:

try:
   import socket  
   socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
   socket.settimeout(10)
except socket.error:
    print("Nope !!!")

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionanonymousView Question on Stackoverflow
Solution 1 - PythonJoão PintoView Answer on Stackoverflow
Solution 2 - PythonJohn La RooyView Answer on Stackoverflow
Solution 3 - PythonHimanshu KanojiyaView Answer on Stackoverflow
Solution 4 - PythonMr.Programmer nopeView Answer on Stackoverflow