Do_handshake() Method Of SSLSocket Class In Python

Method Name:


Method Signature:




Return Value:



  • The method do_handshake() does the TLS handshaking with the peer.
  • While the TLS handshaking can be done as part of connecting with the peer, it can also be opted for later by calling the do_handshake() explicitly.
  • In the Python code example below, if the wrap_socket() method on the SSLContext instance is called with do_handshake_on_connect = True (which is the default behaviour), then the time taken for the connect() will be more as it includes the time for completing the TLS handshake.


TLS Handshake:

The TLS handshake (also still called as SSL handshake) involves exchanging information and deciding on the following for the TLS communication being established:

  • The TLS version 
  • Compression method
  • The cipher suit
  • Validating the identity of server and the client
  • Generation of Session Keys.



# Example Python program that uses an SSLSocket instance to

# connect to a server with SSL handshaking done explicitly through

# do_handshake() method

import socket

import ssl

import platform

import time


# Context creation

sslContext              = ssl.SSLContext();

sslContext.verify_mode  = ssl.CERT_REQUIRED;


# Check for OS X platform

if platform.system().lower() == 'darwin':

    import certifi

    import os


    # Load the CA certificates used for validating the peer's certificate





# Create an SSLSocket                                    

clientSocket        = socket.socket();

secureClientSocket  = sslContext.wrap_socket(clientSocket, do_handshake_on_connect=False);


# Only connect, no handshake

t1 = time.time();

retval = secureClientSocket.connect(("", 443));

print("Time taken to establish the connection:%2.3f"%(time.time() - t1));


# Explicit handshake

t3 = time.time();


print("Time taken for SSL handshake:%2.3f"%(time.time() - t3));



# Get the certificate of the server and print

serverCertificate = secureClientSocket.getpeercert();

print("Certificate obtained from the server:");





Time taken to establish the connection:0.225

Time taken for SSL handshake:0.450

Certificate obtained from the server:

{'subject': ((('countryName', 'US'),), (('stateOrProvinceName', 'California'),), (('localityName', 'Los Angeles'),), (('organizationName', 'Internet Corporation for Assigned Names and Numbers'),), (('organizationalUnitName', 'Technology'),), (('commonName', ''),)), 'issuer': ((('countryName', 'US'),), (('organizationName', 'DigiCert Inc'),), (('commonName', 'DigiCert SHA2 Secure Server CA'),)), 'version': 3, 'serialNumber': '0FD078DD48F1A2BD4D0F2BA96B6038FE', 'notBefore': 'Nov 28 00:00:00 2018 GMT', 'notAfter': 'Dec  2 12:00:00 2020 GMT', 'subjectAltName': (('DNS', ''), ('DNS', ''), ('DNS', ''), ('DNS', ''), ('DNS', ''), ('DNS', ''), ('DNS', ''), ('DNS', '')), 'OCSP': ('',), 'caIssuers': ('',), 'crlDistributionPoints': ('', '')}


Copyright 2023 ©