Socket close platform compatibility High

On some platforms os.close does not work for socket file descriptors. This is most noticeable with Windows.

Detector ID
python/socket-close-platform-compatibility@v1.0
Category
Common Weakness Enumeration (CWE) external icon
-

Noncompliant example

1def create_socket_noncompliant(samplehost, sampleport, samplebuffersize):
2    import socket
3    socket.socket.settimeout(10.0)
4    socket = socket.socket()
5    socket.connect((samplehost, sampleport))
6    print(socket.recv(samplebuffersize))
7    # Noncompliant: socket.shutdown is not called before closing the socket.
8    socket.close()

Compliant example

1def create_socket_compliant(samplehost, sampleport, samplebuffersize):
2    import socket
3    socket.socket.settimeout(10.0)
4    socket = socket.socket()
5    socket.connect((samplehost, sampleport))
6    try:
7        print(socket.recv(samplebuffersize))
8    finally:
9        # Compliant: socket.shutdown is called before closing the socket.
10        socket.shutdown(socket.SHUT_WR)
11        socket.close()