pythonsocketsnetwork-programmingtimeoutpython-sockets

Python Socket accept() Timeout


Using sockets, the below Python code opens a port and waits for a connection. Then, it sends a response when a connection is made.

import socket
ip = 127.0.0.1
port = 80
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((ip, port))
s.listen(1)
conn, addr = s.accept()
conn.send(response)
conn.close()

If a connection is not established within 10 seconds, I would like it to move on. Is there a way to define a timeout for s.accept()?

  s.accept(timeout=10)

Maybe something like the above line?

Thanks in advance for your help!


Solution

  • Use socket.settimeout:

    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.settimeout(10)
    
    timeout = False
    while not timeout:
      try: 
        (conn, addr) = s.accept() 
      except socket.timeout:
        pass
      else:
        # your code
    

    To make a 10 second timeout the default behavior for any socket, you can use

    socket.setdefaulttimeout(10)