Bind() Function Of Socket Module In Python


  • 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(("", 32007));


# Listen for incoming connections



# Start accepting client connections


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


    # Handle one request from client


        data = clientSocket.recv(1024);

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



            # Send back what you received





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(("", 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());



At client: Learning Python is fun


Copyright 2019 ©