Sobes.tech
Junior

How does TCP work?

sobes.tech AI

Answer from AI

TCP (Transmission Control Protocol) is a transport layer protocol that provides reliable, connection-oriented, bidirectional data transfer.

Main stages of operation:

  1. Connection establishment (Three-way handshake):

    • The client sends a SYN (Synchronize) packet with an initial sequence number.
    • The server responds with a SYN-ACK (Synchronize-Acknowledgement) packet, confirming receipt of the client's SYN and sending its own initial sequence number.
    • The client sends an ACK (Acknowledgement) packet, confirming receipt of the server's SYN-ACK.
    • The connection is established.
    // Client -> Server  
    SYN (Seq=X)  
    
    // Server -> Client  
    SYN-ACK (Seq=Y, ACK=X+1)  
    
    // Client -> Server  
    ACK (ACK=Y+1)  
    
  2. Data transfer:

    • Data is segmented.
    • Each segment is numbered for order control.
    • The receiver sends an acknowledgment (ACK) for each successfully received segment.
    • If a segment is not acknowledged within a timeout, the sender retransmits it.
    • Flow control (sliding window) is used to prevent buffer overflow at the receiver.
    • Congestion control mechanisms are employed to adapt the transmission rate to network conditions.
  3. Connection termination (Four-way handshake or three-way during simultaneous close):

    • One side (initiator) sends a FIN (Finish) packet after sending all its data.
    • The other side acknowledges the FIN with an ACK.
    • The other side (when ready) sends its own FIN.
    • The initiator acknowledges the second FIN with an ACK.
    • Both sides enter the TIME_WAIT state to ensure reliable termination.
    // Side 1 -> Side 2  
    FIN (Seq=A)  
    
    // Side 2 -> Side 1  
    ACK (ACK=A+1)  
    
    // (CLOSE_WAIT state on Side 2, can transmit remaining data)  
    
    // Side 2 -> Side 1  
    FIN (Seq=B)  
    
    // Side 1 -> Side 2  
    ACK (ACK=B+1)  
    

Key features:

  • Reliability: Guarantees data delivery in the correct order without loss or duplicates through acknowledgments and retransmissions.
  • Stream-oriented: Data is treated as a continuous byte stream.
  • Connection-oriented: Requires establishing and terminating a session.
  • Flow control: Prevents buffer overflow at the receiver.
  • Congestion control: Adapts transmission speed to network capacity.