Search code examples
pythonsocketsssl

Why does `ssl.SSLContext.wrap_socket` cause socket to close?


I found some "strange" phenomena when using Python for network programming.

After constructing the SSL context and obtaining the SSL socket, the original socket will be automatically closed. Why is this? Is there any need to do this?

Just like the following code:

main.py

ssl_ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
fd = socket.socket()

ssl_fd = ssl_ctx.wrap_socket(fd, server_hostname='www.baidu.com')
print(fd)

The output of this code is as follows:

E:\Projects\_library_py>python main.py
<socket.socket [closed] fd=-1, family=2, type=1, proto=0>

Solution

  • Based on the code in SSLSocket._create it does not actually close the socket but calls socket.detach() to move control over the underlying OS socket from plain socket to SSLSocket. This is likely done so that the programmer does not inadvertently continues to use the plain socket, because reading, writing or closing directly on the plain socket would corrupt the SSLSocket.

    Since the developer is not supposed to use the plain socket directly anymore no harm is done this way, but accidental harm might be prevented.