SSLContext.
wrap_socket
(sock, server_side=False, do_handshake_on_connect=True, suppress_ragged_eofs=True, server_hostname=None, session=None)
SSLContext.
wrap_socket
(sock, server_side=False, do_handshake_on_connect=True, suppress_ragged_eofs=True, server_hostname=None, session=None)Wrap an existing Python socket sock and return an instance of SSLContext.sslsocket_class
(default SSLSocket
). The returned SSL socket is tied to the context, its settings and certificates. sock must be a SOCK_STREAM
socket; other socket types are unsupported.
The parameter server_side
is a boolean which identifies whether server-side or client-side behavior is desired from this socket.
For client-side sockets, the context construction is lazy; if the underlying socket isn’t connected yet, the context construction will be performed after connect()
is called on the socket. For server-side sockets, if the socket has no remote peer, it is assumed to be a listening socket, and the server-side SSL wrapping is automatically performed on client connections accepted via the accept()
method. The method may raise SSLError
.
On client connections, the optional parameter server_hostname specifies the hostname of the service which we are connecting to. This allows a single server to host multiple SSL-based services with distinct certificates, quite similarly to HTTP virtual hosts. Specifying server_hostname will raise a ValueError
if server_side is true.
The parameter do_handshake_on_connect
specifies whether to do the SSL handshake automatically after doing a socket.connect()
, or whether the application program will call it explicitly, by invoking the SSLSocket.do_handshake()
method. Calling SSLSocket.do_handshake()
explicitly gives the program control over the blocking behavior of the socket I/O involved in the handshake.
The parameter suppress_ragged_eofs
specifies how the SSLSocket.recv()
method should signal unexpected EOF from the other end of the connection. If specified as True
(the default), it returns a normal EOF (an empty bytes object) in response to unexpected EOF errors raised from the underlying socket; if False
, it will raise the exceptions back to the caller.
session, see session
.
Changed in version 3.5: Always allow a server_hostname to be passed, even if OpenSSL does not have SNI.
Changed in version 3.6: session argument was added.
Changed in version 3.7: The method returns on instance of SSLContext.sslsocket_class
instead of hard-coded SSLSocket
.
Related Reading