81

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

anonymous
  • 811
  • 1
  • 6
  • 3
  • Yes, python does allow timeout resetting. You can even set a different timeout after makefile. I have tested on linux and windows. – NameOfTheRose Apr 30 '19 at 07:07

4 Answers4

146

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)
Dhia
  • 10,119
  • 11
  • 58
  • 69
João Pinto
  • 5,521
  • 5
  • 21
  • 35
28

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)
John La Rooy
  • 295,403
  • 53
  • 369
  • 502
4

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.
jis0324
  • 205
  • 2
  • 15
  • 2
    Do note in version 3.7.x and perhaps earlier there is also a `sockets.setdefaulttimeout(10.0)` which I think is used by all newly created sockets library objects that take timeouts. – DevPlayer Feb 26 '20 at 15:28
  • Adding to @DevPlayer note, you need to call sockets.setdefaulttimeout(10.0) before creating the socket. Tested with Python 3.10.6. – Michael Apr 06 '23 at 11:37
1

Try this code:

try:
   import socket  
   socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
   socket.settimeout(10)
except socket.error:
    print("Nope !!!")
S.B
  • 13,077
  • 10
  • 22
  • 49