Bind() method of SSLSocket class in Python

Method Name:

bind

Method Signature:

bind()

Parameters:

None

Return Value:

None

Method Overview:

  • The bind() method attaches a socket(Remember, the SSLSocket is derived from the socket class) to an available IP address and a port.
  • The client programs generally do not invoke the bind() method on a socket instance. The reason is the socket will be attached to an ephemeral port when the bind() method is not called.
  • The clients, contact server programs all the times. Hence, a server socket should be attached to a specific IP address and a port number.

Example:

  • The Python program below when executed binds an SSLSocket to a specific port and IP.
  • The client program provided in the Introduction to SSLSocket, can be used to connect to this server.
  • The server responds by sending a the temperature of a city to the client.

# An example Python program that binds to an IP address and port

# using the bind() method of SSLSocket class

# and listens for incoming connections from clients. To the

# clients, it responds with the current temperature of a city.

# The temperature values are simply random values between average high and

# low values.

 

import ssl

import socket

import random

 

# File paths

pemFileName     = "./DemoCA.pem";

certFileName    = "./DemoSvr.crt";

keyFileName     = "./DemoSvr.key";

 

# IP address and Port number

ipAddress       = "127.0.0.1";

portNumber      = 15001;

 

# Socket creation

sock = socket.socket();

 

# SSL context creation

ct              = ssl.SSLContext();

ct.verify_mode  = ssl.CERT_REQUIRED;

 

# Load the certificate of the certificate authority, with which the

# server will validate the client certificate

ct.load_verify_locations(pemFileName)

 

# Load the server certificate

ct.load_cert_chain(certfile=certFileName, keyfile=keyFileName);

 

# Create server socket

serverSocket    = socket.socket();

 

# Make an SSLSocket

secureServerSocket  = ct.wrap_socket(serverSocket,

                                     server_side=True);                                    

 

# Bind the secure socket to a specific IP address and port number

secureServerSocket.bind((ipAddress, portNumber));

 

# Listen to accept connections

secureServerSocket.listen();

print("Temperature server listening for client requests:");

 

while(True):

    (clientConnection, clientIP) = secureServerSocket.accept();

    temp = random.uniform(50, 65);

    tempStr = "Temperature in the city is %2.2f"%temp;

    encoded = tempStr.encode();

    clientConnection.sendall(encoded);

    print("Replied to %s with the temperature value %2.2f"%(clientIP, temp));

 

Output-Server:

Replied to ('127.0.0.1', 51589) with the temperature value 60.22

Replied to ('127.0.0.1', 51592) with the temperature value 53.73

 

Output-Client:

Secure communication received from server:Temperature in the city is 53.73

 


Copyright 2024 © pythontic.com