Socket connection timeout Medium

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.

Detector ID
python/socket-connection-timeout@v1.0
Category

Noncompliant example

1def create_socket_noncompliant(samplehost, sampleport, samplebuffersize):
2    import socket
3    # Noncompliant: socket timeout is not set.
4    socket = socket.create_connection((samplehost, sampleport))
5    try:
6        print(socket.recv(samplebuffersize))
7    finally:
8        socket.close()

Compliant example

1def create_socket_compliant(samplehost, sampleport, samplebuffersize):
2    import socket
3    # Compliant: socket timeout is set.
4    socket = socket.create_connection((samplehost, sampleport), timeout=10)
5    try:
6        print(socket.recv(samplebuffersize))
7    finally:
8        socket.close()