- 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:
# A TCP based echo server
echoSocket = socket.socket();
# Bind the IP address and the port number
# 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:
# 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()
# 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