Bind() Function Of Socket Module In Python

Overview:

  • The bind() method of Python's socket class assigns an IP address and a port number to a socket instance.
  • The bind() method is used when a socket needs to be made a server socket.
  • As server programs listen on published ports, it is required that a port and the IP address to be assigned explicitly to a server socket.
  • For client programs, it is not required to bind the socket explicitly to a port. The kernel of the operating system takes care of assigning the source IP and a temporary port number.
  • The client socket can use the connect() method, after the socket creation is complete to contact the server socket.

 

Example – A Simple Echo Server Program:

import socket

 

# A TCP based echo server

echoSocket = socket.socket();

 

# Bind the IP address and the port number

echoSocket.bind(("127.0.0.1", 32007));

 

# Listen for incoming connections

echoSocket.listen();

 

# Start accepting client connections

while(True):

    (clientSocket, clientAddress) = echoSocket.accept();

   

    # Handle one request from client

    while(True):

        data = clientSocket.recv(1024);

        print("At Server: %s"%data);

 

        if(data!=b''):

            # Send back what you received

            clientSocket.send(data);

            break;

 

Output:

At Server: b'Learning Python is fun'

 

Example – A Simple Echo Client Program:

import socket

 

# Create a TCP based client socket

echoClient =  socket.socket();

 

# Note: No need for bind() call in client sockets...

# Just use the socket by calling connect()

echoClient.connect(("127.0.0.1", 32007));

 

# Send a message

echoClient.send("Learning Python is fun".encode());

 

# Get the reply

msgReceived = echoClient.recv(1024);

 

# Print the reply

print("At client: %s"%msgReceived.decode());

 

Output:

At client: Learning Python is fun

 


Copyright 2023 © pythontic.com