Implementing the TCP server and Client in Python

Implementing the TCP server and Client in Python

TCP (Transmission Control Protocol) is one of the main protocols in the Internet protocol suite. It provides reliable, connection-oriented communication between two devices over a network. TCP ensures that data is delivered in the correct order and without errors. It achieves this by using acknowledgments and retransmissions to handle lost or corrupted data.

TCP Header

The TCP header is part of the TCP packet used for communication. It contains several fields, each serving a specific purpose:

  1. Source Port (16 bits): Identifies the sender’s port number.
  2. Destination Port (16 bits): Identifies the recipient’s port number.
  3. Sequence Number (32 bits): Specifies the sequence number of the first data byte in the current message.
  4. Acknowledgment Number (32 bits): Indicates the next sequence number that the sender is expecting to receive.
  5. Data Offset (4 bits): Specifies the size of the TCP header in 32-bit words.
  6. Reserved (3 bits): Reserved for future use.
  7. Flags (9 bits): Contains control flags such as URG, ACK, PSH, RST, SYN, and FIN.
  8. Window Size (16 bits): Specifies the size of the sender’s receive window, indicating how much data the sender can accept.
  9. Checksum (16 bits): Used for error-checking the header and data.
  10. Urgent Pointer (16 bits): Indicates the end of urgent data if the URG flag is set.
  11. Options (Variable): Optional field used for various purposes, such as Maximum Segment Size (MSS) negotiation.

TCP Server and Client

TCP Server:

A TCP server is a program that listens for incoming TCP connections from clients. It typically follows these steps:

This Python script is a simple TCP server that listens for incoming connections and handles client requests. It utilizes the socket module for socket operations and threading for concurrent handling of client connections.

Import Statements

Python
#!/usr/bin/python

import socket
import threading
  1. Shebang Line: Specifies the interpreter to be used for running the script.
  2. Import Statements:
  • socket: Provides low-level networking functionality.
  • threading: Allows for concurrent execution using threads.

Server Configuration

Python
SERVER_IP   = "127.0.0.1"
SERVER_PORT = 9998
  • Server IP and Port: Defines the IP address and port on which the server will listen for incoming connections.

Socket Creation and Binding

Python
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((SERVER_IP, SERVER_PORT))
  1. Socket Creation: Creates a socket for IPv4 (AF_INET) and TCP (SOCK_STREAM) communication.
  2. Binding: Binds the socket to the specified IP address and port.

Listening for Connections

Python
server.listen(5)
  • Listening: The server is configured to listen for up to 5 incoming connections in the listen queue.

Connection Acceptance

Python
print("[*] Server Listening on %s:%d" % (SERVER_IP, SERVER_PORT))

client, addr = server.accept()
client.send("I am the server accepting connections...".encode())
print("[*] Accepted connection from: %s:%d" % (addr[0], addr[1]))
  1. Print Information: Prints that the server is listening on a specific IP and port.
  2. Accept Connection: Accepts an incoming connection and retrieves the client socket and address.
  3. Sending Initial Message: Sends an initial message to the connected client.

Client Handling Function

Python
def handle_client(client_socket):
    request = client_socket.recv(1024)
    print("[*] Received request : %s from client %s" , request, client_socket.getpeername())
    client_socket.send(bytes("ACK","utf-8"))
  • Function Definition: Defines a function handle_client to process client requests.
  • Request Reception: Receives a request from the client using recv().
  • Prints Request Information: Prints the received request and the client’s address.
  • Sends ACK: Sends an acknowledgment back to the client.

Infinite Loop for Client Handling

Python
while True:
    handle_client(client)
  • Infinite Loop: Repeatedly calls the handle_client function for the connected client.

Closing Sockets

Python
client_socket.close()
server.close()
  • Socket Closure: Closes both the client socket and the server socket after handling the client request.
Python
#!/usr/bin/python

import socket
import threading

SERVER_IP   = "127.0.0.1"
SERVER_PORT = 9998

#  family = Internet, type = stream socket means TCP
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

server.bind((SERVER_IP,SERVER_PORT))

server.listen(5)

print("[*] Server Listening on %s:%d" % (SERVER_IP,SERVER_PORT))

client,addr = server.accept()

client.send("I am the server accepting connections...".encode())

print("[*] Accepted connection from: %s:%d" % (addr[0],addr[1]))

def handle_client(client_socket):
    request = client_socket.recv(1024)
    print("[*] Received request : %s from client %s" , request, client_socket.getpeername())
    client_socket.send(bytes("ACK","utf-8"))

while True:
    handle_client(client)
    
client_socket.close()
server.close()

This script sets up a TCP server that listens for incoming connections, accepts a single connection, sends an initial message, and then enters into an infinite loop to handle client requests. The handle_client function is responsible for processing each client’s request. Note that this script handles only one client connection due to the lack of multi-threading or asynchronous handling.

TCP Client:

A TCP client is a program that initiates a connection to a TCP server. It generally follows these steps:

This Python script is a simple TCP client that connects to a server using sockets. It establishes a connection, sends and receives messages to and from the server, and handles a “quit” command to gracefully terminate the communication.

Import Statement

Python
import socket
  • Import Statement: Imports the socket module for socket operations.

Configuration Parameters

Python
host = "127.0.0.1"
port = 9998
  • Host and Port Configuration: Specifies the target host (server) and port to connect to.

Connection Setup and Message Reception

Python
try:
    mysocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    mysocket.connect((host, port))
    print('Connected to host ' + str(host) + ' in port: ' + str(port))
    message = mysocket.recv(1024)
    print("Message received from the server", message)
  1. Socket Creation: Creates a socket for IPv4 (AF_INET) and TCP (SOCK_STREAM) communication.
  2. Connection Establishment: Connects to the specified host and port.
  3. Connection Confirmation: Prints a message indicating successful connection.
  4. Message Reception: Receives an initial message from the server.

Message Sending Loop

Python
    while True:
        message = input("Enter your message > ")
        mysocket.send(bytes(message.encode('utf-8')))
        if message == "quit":
            break
  1. Infinite Loop: Prompts the user to enter a message and sends it to the server using the send method.
  2. Quit Condition: If the entered message is “quit,” the loop is exited.

Socket Error Handling

Python
except socket.errno as error:
    print("Socket error ", error)
  • Exception Handling: Catches socket-related errors and prints an error message.

Socket Closure

Python
finally:
    mysocket.close()
  • Socket Closure: Ensures that the socket is closed, regardless of whether an exception occurred or not.
Python
#!/usr/bin/python
 
import socket

host="127.0.0.1"
port = 9998

try:
	mysocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
	mysocket.connect((host, port))
	print('Connected to host '+str(host)+' in port: '+str(port))
	message = mysocket.recv(1024)
	print("Message received from the server", message)
	while True:
		message = input("Enter your message > ")
		mysocket.send(bytes(message.encode('utf-8')))
		if message== "quit":
			break
except socket.errno as error:
	print("Socket error ", error)
finally:
	mysocket.close()

This script establishes a TCP connection to a server, receives an initial message, enters an interactive loop to send messages to the server, and terminates when the user enters “quit.” It includes error handling for potential socket errors and ensures proper socket closure in the finally block.

Total
3
Shares

Leave a Reply

Previous Post
Port Scanning with sockets in python

Port Scanning with sockets in python

Next Post
Implementing a simple UDP server and Client in Python

Implementing a simple UDP server and Client in Python

Related Posts