🔗 Tutorial 8: TCP Connection Establishment and Termination (Advanced)

University‑level treatment – COMP347 (TrustOpen University)

Table of Contents

🎯 Learning Objectives

After completing this tutorial, you should be able to:

🔍 Overview

TCP is a connection‑oriented protocol, meaning that before data can be exchanged, a logical connection must be established between the two endpoints. This connection is set up using a three‑way handshake and later terminated using a four‑segment exchange. This tutorial explores the full connection lifecycle, including the state transitions that occur at both client and server, the subtleties of the TIME_WAIT state, and the security implications of SYN floods. We also cover advanced topics such as simultaneous open/close, the use of RST for abortive release, and the keep‑alive timer for detecting dead connections.

📘 1. TCP Connection State Machine Overview

TCP connections are managed by a state machine at each endpoint. The states are:

The state transitions are triggered by events such as sending or receiving SYN, FIN, ACK, or RST segments.

📘 2. Connection Establishment – The Three‑Way Handshake

The three‑way handshake establishes a TCP connection:

  1. Client sends SYN (seq = client ISN, SYN=1) → enters SYN_SENT.
  2. Server replies with SYN‑ACK (seq = server ISN, ACK = client ISN+1, SYN=1, ACK=1) → enters SYN_RCVD.
  3. Client sends ACK (ACK = server ISN+1) → both enter ESTABLISHED.

Purpose:

The sequence numbers allow TCP to detect duplicate segments from old connections and to ensure ordered delivery.

Figure 1: Three‑Way Handshake

Client                          Server
  |                               |
  |   SYN (seq=x)                 |
  |------------------------------>|
  |   SYN‑ACK (seq=y, ACK=x+1)    |
  |<------------------------------|
  |   ACK (ACK=y+1)               |
  |------------------------------>|
  |   Data exchange               |
  |<----------------------------->|

2.1 Initial Sequence Number (ISN) Selection

The ISN is chosen randomly to prevent sequence number prediction attacks (e.g., session hijacking) and to avoid confusion with old connections. The random number is increased over time to meet security requirements.

📘 3. Connection Termination – The Four‑Segment Teardown

Either endpoint can initiate connection termination:

  1. Active closer sends FIN (seq = u) → enters FIN_WAIT_1.
  2. Passive closer replies with ACK (ACK = u+1) → enters CLOSE_WAIT; active closer enters FIN_WAIT_2.
  3. Passive closer sends FIN (seq = v, ACK = u+1) → enters LAST_ACK.
  4. Active closer sends ACK (ACK = v+1) → enters TIME_WAIT; passive closer enters CLOSED.

The TIME_WAIT state lasts for 2 * MSL (Maximum Segment Lifetime, typically 60 seconds). This ensures that the final ACK is delivered and that old segments from this connection expire before the ports are reused.

Figure 2: Four‑Segment Teardown

Active Closer                   Passive Closer
  |                               |
  |   FIN (seq=u)                 |
  |------------------------------>|
  |   ACK (ACK=u+1)               |
  |<------------------------------|
  |   (data may continue)         |
  |   FIN (seq=v)                 |
  |<------------------------------|
  |   ACK (ACK=v+1)               |
  |------------------------------>|
  |   TIME_WAIT (2MSL)            |
  |   then CLOSED                 |

📘 4. TCP State Transition Diagram (Client and Server)

The state diagram shows the transitions for both client and server. The client typically starts in CLOSED, sends SYN (SYN_SENT), receives SYN‑ACK (ESTABLISHED). The server starts in LISTEN, receives SYN (SYN_RCVD), sends SYN‑ACK, receives ACK (ESTABLISHED). For termination, both follow the FIN sequence.

A useful mnemonic: Client states: CLOSED → SYN_SENT → ESTABLISHED → FIN_WAIT_1 → FIN_WAIT_2 → TIME_WAIT → CLOSED. Server: CLOSED → LISTEN → SYN_RCVD → ESTABLISHED → CLOSE_WAIT → LAST_ACK → CLOSED.

📘 5. TIME_WAIT State – Purpose and Duration

The TIME_WAIT state is maintained by the side that initiates the active close (the one that sends the first FIN). Its purposes:

The duration is 2 * MSL, where MSL (Maximum Segment Lifetime) is typically 60 seconds, so TIME_WAIT lasts 120 seconds. This value is configurable in the OS.

📘 6. SYN Flood Attacks and SYN Cookies

SYN flood: An attacker sends a large number of SYN segments with spoofed source IPs. The server responds with SYN‑ACK, allocates resources for each half‑open connection, and waits for the final ACK. Since the ACK never arrives, the server exhausts its memory and connection backlog, preventing legitimate connections.

SYN cookies (RFC 4987): A defense mechanism that does not allocate resources for a SYN until the handshake is complete. The server encodes the connection’s state (ISN, MSS, etc.) into a cookie that is sent back in the SYN‑ACK’s sequence number. When the client returns the ACK, the server can recreate the state from the cookie. This stateless approach mitigates SYN flood attacks.

📘 7. Simultaneous Open and Simultaneous Close

Simultaneous open: Both endpoints send SYN to each other at the same time. Both transition to SYN_SENT, receive the other’s SYN, and reply with SYN‑ACK, then ACK. The connections merge into one. This is rare but supported.

Simultaneous close: Both endpoints send FIN simultaneously. Both enter FIN_WAIT_1, receive FIN from the other, reply with ACK, then enter CLOSING state (instead of FIN_WAIT_2), then TIME_WAIT after receiving ACK for their FIN.

📘 8. Half‑Open Connections and Keep‑Alive Timers

A half‑open connection occurs when one side crashes or becomes unreachable without sending a FIN. The other side may not be aware. To detect this, TCP can use a keep‑alive timer. After a period of inactivity (typically 2 hours), the TCP stack sends a probe segment. If no response is received, the connection is terminated.

📘 9. Connection Reset (RST) and Abortive Release

A connection can be abruptly terminated by sending a segment with the RST flag set. This is used when:

RST tears down the connection without the four‑way handshake; both sides immediately enter CLOSED.

📘 10. Advanced Topics: Port Reuse, SO_REUSEADDR, and TIME_WAIT

The TIME_WAIT state can cause port exhaustion on busy servers. The SO_REUSEADDR socket option allows a new socket to bind to a port that is in TIME_WAIT, enabling rapid restart of a server. However, it must be used carefully to avoid receiving stale data. The SO_LINGER option can also be used to control the closing behaviour.

📝 Quiz

Test your understanding with these 35 questions. Answers are hidden below each.

  1. How many segments are exchanged in the TCP three‑way handshake?
    Answer3 segments.
  2. What is the purpose of the SYN flag in the handshake?
    AnswerTo synchronize sequence numbers and initiate a connection.
  3. What is the purpose of the ACK flag in the handshake?
    AnswerTo acknowledge the SYN, indicating that the SYN was received.
  4. What is the Initial Sequence Number (ISN) and how is it chosen?
    AnswerISN is the starting sequence number; it is chosen randomly to avoid security attacks and confusion with old connections.
  5. In the three‑way handshake, what does the client send in the ACK after receiving SYN‑ACK?
    AnswerIt sends ACK with acknowledgment number = server ISN + 1.
  6. What state does the client enter after sending the first SYN?
    AnswerSYN_SENT.
  7. What state does the server enter after receiving a SYN and sending SYN‑ACK?
    AnswerSYN_RCVD.
  8. How many segments are exchanged in the typical connection teardown?
    Answer4 segments (FIN, ACK, FIN, ACK).
  9. What flag is used to initiate connection termination?
    AnswerFIN.
  10. What state does the active closer enter after sending FIN?
    AnswerFIN_WAIT_1.
  11. What state does the passive closer enter after receiving FIN and sending ACK?
    AnswerCLOSE_WAIT.
  12. What state does the active closer enter after receiving ACK for its FIN?
    AnswerFIN_WAIT_2.
  13. What state does the passive closer enter after sending FIN?
    AnswerLAST_ACK.
  14. What state does the active closer enter after sending the final ACK?
    AnswerTIME_WAIT.
  15. What is the purpose of the TIME_WAIT state?
    AnswerTo ensure the final ACK is received and to allow old segments to expire before port reuse.
  16. How long does TIME_WAIT typically last?
    Answer2 * MSL (Maximum Segment Lifetime), typically 120 seconds.
  17. What is a SYN flood attack?
    AnswerAn attack where an attacker sends many SYN segments with spoofed IPs, causing the server to allocate resources for half‑open connections and exhaust its memory.
  18. What is a SYN cookie?
    AnswerA mechanism that encodes connection state in the SYN‑ACK’s sequence number to avoid allocating resources until the handshake completes, mitigating SYN floods.
  19. What is a simultaneous open?
    AnswerWhen both endpoints send SYN to each other at the same time, merging into a single connection.
  20. What is a simultaneous close?
    AnswerWhen both endpoints send FIN at the same time, leading to the CLOSING state.
  21. What is a half‑open connection?
    AnswerA connection where one side has crashed or is unreachable, but the other side still believes the connection is open.
  22. How does TCP detect half‑open connections?
    AnswerUsing keep‑alive timers that send probes to check if the other side is responsive.
  23. What is the RST flag used for?
    AnswerTo abruptly reset (abort) a connection.
  24. When does a server send RST?
    AnswerWhen a SYN arrives for a port with no listening socket, or when a segment arrives for a non‑existent connection.
  25. What is the difference between normal close and abortive release (RST)?
    AnswerNormal close uses FIN/ACK to gracefully terminate; abortive release uses RST to immediately terminate without exchanging FIN.
  26. What is the MSL (Maximum Segment Lifetime)?
    AnswerThe maximum time a TCP segment can exist in the network before being discarded, typically 60 seconds.
  27. Why is TIME_WAIT duration 2*MSL?
    AnswerTo ensure that any delayed segments from the connection expire before the same ports can be reused.
  28. What is the SO_REUSEADDR socket option?
    AnswerIt allows a socket to bind to a port that is in TIME_WAIT state, enabling rapid server restart.
  29. What is the SO_LINGER option?
    AnswerIt controls the behaviour of the socket when data is queued and close() is called; can force abortive release.
  30. What is the TCP keep‑alive timer default in many systems?
    Answer2 hours of inactivity before sending probes.
  31. What happens if a keep‑alive probe receives no response?
    AnswerThe connection is terminated.
  32. Can a connection be in TIME_WAIT on both sides?
    AnswerOnly the side that initiated the close goes into TIME_WAIT; the other side goes to CLOSED.
  33. What is the purpose of the SYN‑ACK in the handshake?
    AnswerTo acknowledge the client’s SYN and to send the server’s SYN with its ISN.
  34. What happens if the client’s ACK in the third step is lost?
    AnswerThe server will retransmit the SYN‑ACK; the client will respond with ACK again.
  35. What is the difference between CLOSE_WAIT and LAST_ACK?
    AnswerCLOSE_WAIT is the state after receiving FIN and ACKing it, waiting for the application to close; LAST_ACK is after sending FIN, waiting for the final ACK.

🛠️ Exercises

Apply your knowledge with these 20 exercises. Solutions are provided below each.

  1. Exercise 1: Sequence Numbers in Handshake
    Client sends SYN with seq=1000. Server sends SYN‑ACK with seq=2000, ACK=1001. What is the client’s ACK number?
    SolutionACK = 2001.
  2. Exercise 2: State Transitions (Client)
    A client initiates a connection, sends SYN, receives SYN‑ACK, sends ACK. What are the client’s states in order?
    SolutionCLOSED → SYN_SENT → ESTABLISHED.
  3. Exercise 3: State Transitions (Server)
    A server listens, receives SYN, sends SYN‑ACK, receives ACK. What are the server’s states?
    SolutionLISTEN → SYN_RCVD → ESTABLISHED.
  4. Exercise 4: Termination States (Active Close)
    Client initiates close: sends FIN, receives ACK, receives FIN, sends ACK. What are the client’s states?
    SolutionESTABLISHED → FIN_WAIT_1 → FIN_WAIT_2 → TIME_WAIT → CLOSED.
  5. Exercise 5: Termination States (Passive Close)
    Server receives FIN, sends ACK, sends FIN, receives ACK. What are the server’s states?
    SolutionESTABLISHED → CLOSE_WAIT → LAST_ACK → CLOSED.
  6. Exercise 6: TIME_WAIT Duration
    If MSL=30 seconds, how long does TIME_WAIT last?
    Solution2 * 30 = 60 seconds.
  7. Exercise 7: SYN Flood Mitigation
    How does SYN cookies prevent resource exhaustion?
    SolutionIt does not allocate resources until the handshake completes; it encodes state in the SYN‑ACK’s sequence number, so the server can reconstruct the state when the ACK arrives.
  8. Exercise 8: Simultaneous Open Sequence
    Both hosts send SYN at the same time. Describe the sequence of segments.
    SolutionBoth send SYN, both receive SYN and send SYN‑ACK, both receive SYN‑ACK and send ACK. Connection established.
  9. Exercise 9: Simultaneous Close
    Both hosts send FIN simultaneously. Describe the states.
    SolutionBoth enter FIN_WAIT_1, receive FIN, send ACK, enter CLOSING, then TIME_WAIT after receiving ACK.
  10. Exercise 10: Half‑Open Detection
    A server has a connection that has been idle for 3 hours. What does it do?
    SolutionIt sends a keep‑alive probe to check if the client is still alive.
  11. Exercise 11: RST Usage
    A client sends data to a server but the server has closed the connection. What does the server send?
    SolutionRST segment to abort the connection.
  12. Exercise 12: SO_REUSEADDR Effect
    A server crashes and restarts quickly. Why might it need SO_REUSEADDR?
    SolutionTo bind to the same port that is still in TIME_WAIT from the previous instance.
  13. Exercise 13: Lost Final ACK
    In termination, the active closer sends the final ACK, but it is lost. What happens?
    SolutionThe passive closer will retransmit its FIN; the active closer sends another ACK. The active closer stays in TIME_WAIT until the retransmission is handled.
  14. Exercise 14: SYN Cookie Example
    Explain how a server uses SYN cookies to handle a SYN flood.
    SolutionWhen a SYN arrives, the server computes a cookie based on the client’s IP, port, and a secret. It sends SYN‑ACK with that cookie as the sequence number. When the ACK arrives, it verifies the cookie and creates the connection state.
  15. Exercise 15: State Diagram Reading
    From the TCP state diagram, what transition leads from SYN_RCVD to ESTABLISHED?
    SolutionReceipt of an ACK for the SYN‑ACK.
  16. Exercise 16: FIN vs RST
    Why would an application choose RST instead of FIN?
    SolutionIf the application detects an error or wants to abort immediately, it sends RST to tear down the connection without waiting for graceful termination.
  17. Exercise 17: TIME_WAIT and Port Reuse
    Can a new connection use the same 4‑tuple while the old one is in TIME_WAIT?
    SolutionNormally no, because the 4‑tuple is still in use. With SO_REUSEADDR, it can be allowed, but the kernel may still protect against old segments.
  18. Exercise 18: MSL Value
    Why is MSL typically 60 seconds?
    SolutionIt is a conservative value based on the assumption that IP datagrams cannot survive longer than that in the Internet.
  19. Exercise 19: Half‑Open Connection Detection
    What is the purpose of the keep‑alive timer in detecting half‑open connections?
    SolutionIt sends probes to the peer; if no response, it assumes the connection is dead and closes it.
  20. Exercise 20: Abortive Release
    What happens to data in transit when RST is sent?
    SolutionData in flight is discarded; the connection is aborted without delivery guarantees.

📚 Homework

These advanced problems require synthesis, research, and quantitative analysis. Sample answers are provided below.

  1. Problem 1: Derive the state transitions for a client that sends SYN, receives SYN‑ACK, but the ACK is lost. What happens?
    Sample AnswerClient sends SYN, enters SYN_SENT. Receives SYN‑ACK, enters ESTABLISHED (even before sending ACK? Actually, the client transitions to ESTABLISHED upon receiving SYN‑ACK, but if ACK is lost, the server remains in SYN_RCVD. The server will retransmit SYN‑ACK; client will ACK again.
  2. Problem 2: Explain why TIME_WAIT is necessary for reliable connection teardown. Provide a scenario where not having TIME_WAIT could cause data corruption.
    Sample AnswerWithout TIME_WAIT, a new connection using the same 4‑tuple could receive old segments from the previous connection, causing corruption. TIME_WAIT ensures old segments expire.
  3. Problem 3: Compare SYN cookies with SYN cache. Which is more effective against attacks? What are the trade‑offs?
    Sample AnswerSYN cookies are stateless and can handle large floods without resource exhaustion. SYN cache allocates limited resources; may be overwhelmed. Cookies have CPU cost for computation but no memory.
  4. Problem 4: Describe the TCP state transitions for a simultaneous open. Show the segment exchange and the states at each step.
    Sample AnswerBoth send SYN (SYN_SENT), both receive SYN and send SYN‑ACK (SYN_RCVD), both receive SYN‑ACK and send ACK (ESTABLISHED). No separate listening socket needed.
  5. Problem 5: What is the impact of a large TIME_WAIT duration on a high‑traffic server? Propose solutions to mitigate port exhaustion.
    Sample AnswerLarge TIME_WAIT can cause ephemeral port exhaustion and prevent server restarts. Solutions: reduce TIME_WAIT duration (if safe), use SO_REUSEADDR, use SO_LINGER with abortive close, or increase the ephemeral port range.
  6. Problem 6: Explain the role of the RST flag in defending against SYN floods (e.g., with TCP reset attacks).
    Sample AnswerRST can be used to close half‑open connections, but attackers can also send forged RST to terminate legitimate connections. Defenses include sequence number validation and TCP timestamps.
  7. Problem 7: Derive the maximum number of concurrent TCP connections a server can support given a single IP and port, assuming no port reuse and ephemeral ports from 49152 to 65535 for clients. What about with SO_REUSEADDR?
    Sample AnswerMax connections = number of clients * ports per client. With a single server IP and port, each client can have up to (65535-49152+1)=16384 connections to that server. With SO_REUSEADDR, multiple server sockets can bind to the same port, but that doesn't increase total connections for a single socket.
  8. Problem 8: Discuss the security implications of predictable ISNs. How does randomization prevent session hijacking?
    Sample AnswerPredictable ISNs allow attackers to guess sequence numbers and inject spoofed segments. Randomization makes guessing infeasible, protecting against hijacking.
  9. Problem 9: What is the difference between the CLOSING and TIME_WAIT states? When does a connection enter CLOSING?
    Sample AnswerCLOSING occurs during simultaneous close when both sides have sent FIN but have not yet received ACKs. TIME_WAIT is after the final ACK is sent and the connection waits for old segments to expire.
  10. Problem 10: Explain the purpose of the TCP keep‑alive mechanism. Is it part of the TCP standard? Discuss its advantages and disadvantages.
    Sample AnswerKeep‑alive is an optional feature to detect dead connections. It is not part of the core standard (RFC 1122). Advantages: detect half‑open connections; disadvantages: overhead and can cause unnecessary traffic.
  11. Problem 11: Describe the effect of setting SO_LINGER with a timeout of 0 on connection termination.
    Sample AnswerSO_LINGER with timeout 0 causes an abortive release (RST) when close() is called, discarding any pending data and immediately closing the connection.
  12. Problem 12: How does TCP handle the case where a SYN segment is received for a connection that is in TIME_WAIT state?
    Sample AnswerIf a SYN arrives for a connection in TIME_WAIT, it may be either a new connection attempt or a duplicate SYN from the old connection. The kernel may reject it if the sequence number does not match the expected ISN, or allow it if it’s a new connection (depending on timestamps).
  13. Problem 13: Explain the concept of "half‑open" connections and how they can be detected using the keep‑alive timer. What are the default keep‑alive settings in Linux?
    Sample AnswerHalf‑open: one side dead, other side unaware. Keep‑alive sends probes; Linux defaults: tcp_keepalive_time = 7200 seconds, tcp_keepalive_intvl = 75 seconds, tcp_keepalive_probes = 9.
  14. Problem 14: Describe a scenario where an application might want to use SO_REUSEADDR and one where it should not.
    Sample AnswerUse: server restart quickly. Should not: if there is a risk of receiving stale data from the previous connection, especially if the connection state is not fully cleared.
  15. Problem 15: Provide a detailed explanation of the TCP state transitions for a server that receives a SYN, sends SYN‑ACK, then receives a RST instead of ACK. What state does it enter?
    Sample AnswerServer: LISTEN → SYN_RCVD. On receiving RST, it transitions to LISTEN (or CLOSED?) The server will drop the half‑open connection and return to LISTEN state, ready for new connections.

📌 Summary

In the next tutorial, we will explore TCP Congestion Control.

COMP347 – Computer Networks (Rev. 10) · TrustOpen University · Based on Kurose & Ross, Computer Networking: A Top‑Down Approach, 9th ed. (2025).