Method Name:
accept
Method Signature:
accept()
Parameters:
None
Return Value:
A tuple containing an SSLSocket instance, which can be used to communicate with the client and the IP address of the client.
Overview:
- The method accept(), accepts a connection request from a client.
- The method accept() returns a tuple of SSLSocket and the IP address of the client.
- The first element of the tuple, which is an instance of SSLSocket that can be used for communicating with the client in a secure manner as per TLS protocol.
- This approach can be compared with the example in Introduction to the SSLSocket where the server Socket is not an SSLSocket and explicit wrapping of the client socket is required using ssl.wrap_socket() to get an SSLSocket to talk to the client. Since, ssl.wrap_socket()is deprecated, the approach used in this example is preferred over the former.
- The client program used in the Introduction to SSLSocket, can be used for communicating with the server below.
Example:
# Example Python program that accepts new TLS connections # from clients through accept() method of SSLSocket class import socket import ssl import platform import certifi import os
# Create an SSL context context = ssl.SSLContext(); context.verify_mode = ssl.CERT_REQUIRED;
# Load CA certificate with which the server will validate the client certificate context.load_verify_locations("./DemoCA.pem")
# Load server certificate context.load_cert_chain(certfile="./DemoSvr.crt", keyfile="./DemoSvr.key")
# Create a connection oriented server socket ipAddress = "127.0.0.1"; portNumber = 15001; serverSocket = socket.socket();
# Wrap the socket to get an SSLSocket and bind it to an IP address and port secureServerSocket = context.wrap_socket(serverSocket, server_side=True); secureServerSocket.bind((ipAddress, portNumber)); secureServerSocket.listen();
print("Listening and accepting connections"); try: while(True): (secureClientConnection, clientAddress) = secureServerSocket.accept(); print("Serving connection request from:"); print(clientAddress); secureClientConnection.sendall("hi there".encode()); secureClientConnection.close(); except KeyboardInterrupt: print("Server exiting"); serverSocket.close(); secureServerSocket.close(); |
Output-Server:
Listening and accepting connections Serving connection request from: ('127.0.0.1', 51035) Serving connection request from: ('127.0.0.1', 51036) ^CServer exiting |
Output-Client:
Secure communication received from server:hi there |