bind() function of socket module in Python

The bind() function assigns an IP address and a port number to a socket. Generally, bind() is called on server sockets as it is required for server programs to publish their IP address and Port number for the to connect to them. The Python examples implement a simple echo server and echo client using the socket functions.

socket Updated 25 Jun 2019 1 min read

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

python
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

Output
At Server: b'Learning Python is fun'

Example – A Simple Echo Client Program

python
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

Output
At client: Learning Python is fun