Course contentsShow
← Computer Science
Lesson 1482 of 2,87234. Internet Protocol SuiteFree lesson

TCP States and State Machine

The finite state machine governing TCP connections: LISTEN, SYN_SENT, ESTABLISHED, CLOSE_WAIT, and other states.

TCP States and State Machine

You'll learn: How TCP uses a finite state machine to track and manage each stage of a connection's lifecycle.

What Is the TCP State Machine?

TCP isn't just "connected" or "disconnected"—it moves through a well-defined sequence of states as connections open, transfer data, and close. Think of it like a restaurant reservation system: you don't go from "no table" to "eating" instantly. You pass through "requested," "confirmed," "seated," and eventually "finished" states. Each state represents where you are in the process.

The TCP state machine is a formal model with approximately 11 states that govern every TCP connection. Both client and server maintain their own state, and specific events (like receiving a SYN packet or calling close()) trigger state transitions.

Key TCP States

  • LISTEN: Server is waiting for incoming connection requests
  • SYN_SENT: Client sent a SYN and is waiting for SYN-ACK
  • SYN_RECEIVED: Server received SYN, sent SYN-ACK, awaiting ACK
  • ESTABLISHED: Three-way handshake complete; data transfer happens here
  • FIN_WAIT_1, FIN_WAIT_2: Active closer is shutting down
  • CLOSE_WAIT: Passive side received FIN but hasn't closed yet
  • CLOSING: Both sides closing simultaneously (rare)
  • TIME_WAIT: Connection closed, waiting to ensure remote received final ACK
  • CLOSED: Connection fully terminated

Why It Matters

The state machine ensures orderly, predictable behavior. For example, you can't send data before reaching ESTABLISHED, and TIME_WAIT prevents old packets from corrupting new connections using the same ports.

Understanding states helps diagnose issues: seeing many connections stuck in CLOSE_WAIT suggests your application isn't closing sockets properly.

Key Takeaway:
TCP's finite state machine orchestrates connection setup, data transfer, and teardown through well-defined states, ensuring reliable and orderly communication between endpoints.