Understanding TCP: Three‑Way Handshake, Data Transfer, and Four‑Way Teardown with Python and Wireshark
This article explains TCP fundamentals—including the three‑way handshake, data transmission, and four‑way connection termination—by building a local Python TCP server and client, capturing the traffic with Wireshark, and analyzing each packet in detail.
The author introduces TCP as a connection‑oriented, reliable transport‑layer protocol defined by RFC 793, and places it in the OSI model (layer 4) and the TCP/IP suite.
Using Python on macOS, a simple TCP server listening on port 20000 is created with socketserver.BaseRequestHandler and TCPServer , while a client uses the socket module to connect, send data, and shut down the connection.
from socketserver import BaseRequestHandler, TCPServer
class EchoHandler(BaseRequestHandler):
def handle(self):
print('Got connection from', self.client_address)
while True:
msg = self.request.recv(8192)
if not msg:
break
self.request.send(msg)
if __name__ == '__main__':
serv = TCPServer(('', 20000), EchoHandler)
serv.serve_forever()The client script creates a socket, connects to localhost:20000 , sends the bytes b'AB' , receives the echo, and finally calls s.shutdown(2) to close the connection.
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('localhost', 20000))
s.send(b'AB')
response = s.recv(8192)
s.shutdown(2)Wireshark is used to capture the entire communication, illustrating the three‑way handshake (SYN, SYN‑ACK, ACK), the data exchange (sequence and acknowledgment numbers, flags such as PSH and ACK), a TCP Window Update, and the four‑step termination (FIN‑ACK sequence). Each step is accompanied by diagrams showing source/destination ports, sequence numbers, and flag values.
The article also briefly explains related concepts such as byte vs. bit, ASCII encoding, and hexadecimal conversion, providing a practical reference for anyone learning socket programming and TCP packet analysis.
References include Wireshark tutorials, TCP/IP textbooks, and Python networking documentation.
360 Tech Engineering
Official tech channel of 360, building the most professional technology aggregation platform for the brand.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.