1. Background
As a software engineer with nearly 6 years of experience, my daily work primarily involves two main aspects: first, handling business logic within specified services, and second, retrieving data from other services or databases. This has sparked my curiosity about how HTTP APIs works? What are the TCP header, three-way, four-way handshake and SYN, ACK, FIN flag? Why are they necessary? Let’s deep dive into these concepts in this blog. Enjoy!
2. Env Preparation
I just built a simple Flask app with a POST RESTful API and deployed it on a remote server. You can call it using curl commands or Postman.
from flask import Flask, jsonify, request app = Flask(__name__) @app.route("/user/login", methods=['POST']) def login(): data = request.get_json() username = data['username'] password = data['password'] return jsonify({ 'code': 200, 'message': 'Login successful', 'data': { 'username': username } }) if __name__ == "__main__": app.run(debug=True)
3. TCP Connection Lifecycle
- Three-way Handshake establishes a reliable TCP connection between the client and the server.
- The client sends a SYN (synchronize) packet to initiate the connection.
- The server responds with a SYN-ACK packet.
- The client sends a ACK (acknowledge) packet back to the server.
- Once the connection is established, the client and server exchange data packets.
- The PSH flag is used to indicate that the data being sent should be immediately delivered to the application layer, without waiting to fill the buffer or for additional data packets.
- The four-way handshake is used to gracefully terminate the TCP connection.
- The server sends a FIN (finish) packet to indicate it wants to close the connection.
- The client acknowledges the server’s FIN request by responding with an ACK packet.
- The client sends its own FIN packet to indicate it is ready to close the connection.
- The server acknowledges the server’s FIN packet with an ACK, completing the termination process.