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:
- Source Port (16 bits): Identifies the sender’s port number.
- Destination Port (16 bits): Identifies the recipient’s port number.
- Sequence Number (32 bits): Specifies the sequence number of the first data byte in the current message.
- Acknowledgment Number (32 bits): Indicates the next sequence number that the sender is expecting to receive.
- Data Offset (4 bits): Specifies the size of the TCP header in 32-bit words.
- Reserved (3 bits): Reserved for future use.
- Flags (9 bits): Contains control flags such as URG, ACK, PSH, RST, SYN, and FIN.
- Window Size (16 bits): Specifies the size of the sender’s receive window, indicating how much data the sender can accept.
- Checksum (16 bits): Used for error-checking the header and data.
- Urgent Pointer (16 bits): Indicates the end of urgent data if the URG flag is set.
- 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
#!/usr/bin/python
import socket
import threading- Shebang Line: Specifies the interpreter to be used for running the script.
- Import Statements:
socket: Provides low-level networking functionality.threading: Allows for concurrent execution using threads.
Server Configuration
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
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((SERVER_IP, SERVER_PORT))- Socket Creation: Creates a socket for IPv4 (AF_INET) and TCP (SOCK_STREAM) communication.
- Binding: Binds the socket to the specified IP address and port.
Listening for Connections
server.listen(5)- Listening: The server is configured to listen for up to 5 incoming connections in the listen queue.
Connection Acceptance
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]))- Print Information: Prints that the server is listening on a specific IP and port.
- Accept Connection: Accepts an incoming connection and retrieves the client socket and address.
- Sending Initial Message: Sends an initial message to the connected client.
Client Handling Function
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_clientto 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
while True:
handle_client(client)- Infinite Loop: Repeatedly calls the
handle_clientfunction for the connected client.
Closing Sockets
client_socket.close()
server.close()- Socket Closure: Closes both the client socket and the server socket after handling the client request.
#!/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
import socket- Import Statement: Imports the
socketmodule for socket operations.
Configuration Parameters
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
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)- Socket Creation: Creates a socket for IPv4 (AF_INET) and TCP (SOCK_STREAM) communication.
- Connection Establishment: Connects to the specified host and port.
- Connection Confirmation: Prints a message indicating successful connection.
- Message Reception: Receives an initial message from the server.
Message Sending Loop
while True:
message = input("Enter your message > ")
mysocket.send(bytes(message.encode('utf-8')))
if message == "quit":
break- Infinite Loop: Prompts the user to enter a message and sends it to the server using the
sendmethod. - Quit Condition: If the entered message is “quit,” the loop is exited.
Socket Error Handling
except socket.errno as error:
print("Socket error ", error)- Exception Handling: Catches socket-related errors and prints an error message.
Socket Closure
finally:
mysocket.close()- Socket Closure: Ensures that the socket is closed, regardless of whether an exception occurred or not.
#!/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.