CCNA online course

Transmission Control Protocol (TCP) Explained

Learn how TCP provides reliable, ordered, connection-oriented transport using ports, handshakes, acknowledgments, retransmissions, flow control, and connection termination.

Transmission Control Protocol (TCP) is a core protocol in the TCP/IP suite. It operates at the Transport layer, which corresponds to OSI Layer 4. TCP provides application-to-application communication between hosts, while IP delivers packets from one host to another.

TCP operates above IP and below application protocols such as HTTP, HTTPS, SSH, FTP, SMTP, IMAP, POP3, and many database protocols. For background, review the OSI reference model.

TCP's Place in Networking

An application does not normally send data directly to an Ethernet interface or an IP routing process. Instead, application data moves down the protocol stack. TCP adds transport information, IP adds addressing information, and the data-link layer prepares a frame for the local network.

Application protocols: HTTP, HTTPS, SSH, SMTP, databases
                         |
Transport layer:         TCP
                         |
Internet layer:         IP
                         |
Network access:          Ethernet, Wi-Fi, and other link protocols

IP is responsible for best-effort delivery between host addresses. IP does not, by itself, guarantee that data arrives, arrives only once, or arrives in order. TCP adds those end-to-end transport functions and uses port numbers to deliver data to the correct application.

What TCP Provides

  • Connection-oriented operation: endpoints establish connection state before normal application data is exchanged.
  • Reliable delivery: acknowledgments, checksums, sequence numbers, and retransmission help recover from loss and detect corruption.
  • Ordered byte-stream delivery: the application receives bytes in their intended order, even if network segments arrive out of order.
  • Full-duplex communication: both endpoints can send and receive independently over the same connection.
  • Application multiplexing: source and destination ports identify the participating applications.
  • Flow control: the receiver can limit how much unacknowledged data the sender transmits.
  • Congestion control: the sender adjusts transmission to reduce harm to a congested network.

These features require header fields, connection state, buffers, acknowledgments, and additional traffic. TCP reliability therefore introduces overhead, possible setup latency, and processing requirements. TCP is not automatically the best choice for every application; the application chooses TCP or UDP according to its requirements.

Common TCP Applications

Applications that need dependable, ordered delivery commonly use TCP. Examples include HTTP and HTTPS web sessions, SSH, FTP control and data connections, SMTP, IMAP, POP3, and many database connections. HTTPS also uses TLS above TCP, so TCP first provides the ordered byte stream used by the TLS and HTTP exchanges.

Applications that prioritize minimal delay, tolerate some loss, or implement reliability themselves may choose UDP instead. A transport protocol should be selected based on application behavior, not on the assumption that TCP is universally better.

Ports, Sockets, and Connection Identification

A port number is a 16-bit Transport-layer identifier used to direct traffic to a service or application. A socket is an endpoint represented by an IP address and a port number. A TCP connection is uniquely identified by four values:

  • Source IP address
  • Source port
  • Destination IP address
  • Destination port

A server commonly listens on a well-known or registered port. For example, an HTTPS server normally listens on TCP port 443. A client normally uses a temporary ephemeral port as its source port. A browser connection might therefore look like this:

Client: 192.0.2.25:49152
Server: 198.51.100.20:443
Protocol: TCP

The IP addresses identify hosts, while the ports identify applications on those hosts. Network address translation can change addresses and ports as traffic crosses a translation device.

The TCP Three-Way Handshake

Before exchanging ordinary application data, TCP endpoints establish state and synchronize initial sequence numbers. The usual client-server exchange is the three-way handshake:

  1. The client sends a segment with the SYN flag. It proposes an initial sequence number.
  2. The server responds with SYN and ACK. It acknowledges the client's SYN and proposes its own initial sequence number.
  3. The client sends an ACK acknowledging the server's SYN.
Client                                      Server
  |  SYN, sequence = 1000                    |
  |----------------------------------------->|
  |  SYN-ACK, sequence = 5000, ack = 1001    |
  |<-----------------------------------------|
  |  ACK, ack = 5001                          |
  |----------------------------------------->|
  |       Connection established              |

A SYN consumes one sequence-number position, which is why the acknowledgment for a SYN with sequence number 1000 is normally 1001. After the handshake, data can begin, subject to negotiated options and the receiver's and network's limits.

Important Handshake States

StateMeaning
LISTENA server is waiting for an incoming connection request.
SYN-SENTAn endpoint has sent a SYN and is waiting for a response.
SYN-RECEIVEDAn endpoint has received a SYN, sent a SYN-ACK, and is waiting for the final ACK.
ESTABLISHEDThe connection is ready for normal bidirectional data transfer.

TCP Data Transfer and Ordered Delivery

TCP presents a continuous byte stream to an application. It divides that stream into TCP segments, each containing a TCP header and a portion of application data. At the destination, TCP validates, reorders, and reassembles the segments before delivering the stream to the application.

A sequence number identifies a position in the byte stream. It is not merely a simple packet identifier. If a segment begins with sequence number 1001 and contains 500 bytes, its bytes occupy positions 1001 through 1500.

An acknowledgment number identifies the next byte the receiver expects. An acknowledgment number of 1501 means that bytes through 1500 have been received in order. TCP acknowledgments are commonly cumulative: one acknowledgment can confirm an entire contiguous range of bytes.

If a later segment arrives before an earlier segment, the receiver may keep the later bytes in a buffer but cannot advance cumulative acknowledgment progress past the missing bytes. Once the missing data arrives, TCP can combine the buffered data and deliver the complete stream in order.

Reliability and Error Recovery

Checksums and Corruption

The TCP checksum detects corruption in the TCP header and payload. Its calculation also includes an IP pseudo-header, containing selected source and destination IP information, the protocol value, and the TCP length. This helps detect delivery to an unexpected protocol or address context.

TCP detects corruption; it does not correct corrupted bits. A segment that fails checksum validation is discarded. The sender eventually retransmits the missing data if its acknowledgment does not arrive.

Retransmission and Duplicate Acknowledgments

If an expected acknowledgment does not arrive before the retransmission timeout, TCP presumes that data or an acknowledgment was lost and retransmits the relevant data. TCP can also use duplicate acknowledgments as a signal that a later segment arrived while an earlier byte range is still missing. A common response is fast retransmit, which resends the suspected missing data before the normal timeout expires.

Sender sends:   bytes 1001-1500, 1501-2000, 2001-2500
Network loses:  bytes 1501-2000
Receiver gets:  first and third ranges
Receiver ACKs:  acknowledgment remains 1501
Sender sees:    duplicate ACKs or a timeout
Sender sends:   bytes 1501-2000 again

After the missing range arrives, the receiver can acknowledge the complete contiguous stream and deliver the bytes in order. TCP reliability is end-to-end between the participating endpoints. It does not guarantee that the application permanently processes, saves, or acts on the data after TCP delivers it.

Flow Control

Flow control protects the receiving host. TCP maintains a receive buffer, and the receiver advertises the amount of available capacity in the receive window, also called the advertised window. The sender limits the amount of unacknowledged data so it does not overrun that buffer.

For example, if a slow application causes the receive buffer to fill, the advertised window decreases. The sender must reduce its outstanding data. If the receiver advertises a zero window, the sender pauses normal data transmission and waits for a window update. When the application consumes buffered data, the receiver can advertise more available space.

The original receive-window field is 16 bits. During the handshake, endpoints can negotiate window scaling, a TCP option that multiplies the usable window and supports high-bandwidth, high-latency paths.

Congestion Control

Flow control and congestion control solve different problems:

  • Flow control protects the receiving host from receiving more data than its buffer can hold.
  • Congestion control responds to conditions in the network, such as queue buildup and loss.

The sender maintains a congestion window, or congestion window limit, based on its estimate of network capacity. In simplified terms, the amount of data that can be in flight is constrained by both the advertised receive window and the congestion window. The effective limit is approximately the smaller of the two.

TCP commonly begins with slow start, increasing its sending rate rapidly while learning the path capacity. It then uses congestion avoidance to grow more cautiously. Packet loss, duplicate acknowledgments, or a timeout can cause TCP to reduce its sending rate and congestion window. Congestion can therefore create loss, retransmissions, increased delay, and reduced throughput.

TCP Segment Header

A TCP header is at least 20 bytes long. Options can extend it to a maximum of 60 bytes. The data offset field tells the receiver where the payload begins.

FieldSize or locationPurposeKey teaching note
Source port16 bitsIdentifies the sending application.Often an ephemeral client port.
Destination port16 bitsIdentifies the receiving service.For example, TCP 443 for HTTPS.
Sequence number32 bitsIdentifies the byte position of transmitted data.SYN and FIN consume sequence space.
Acknowledgment number32 bitsIdentifies the next byte expected.Valid when ACK is set.
Data offset4 bitsSpecifies the TCP header length.Locates the beginning of payload data.
Reserved bitsReserved areaReserved for future use.Normally transmitted as zero and ignored according to protocol rules.
Control flagsControl-bit areaIndicates connection and data-control functions.Includes SYN, ACK, FIN, RST, PSH, and URG; modern TCP also uses ECE and CWR.
Receive window16 bits before scalingAdvertises available receive-buffer capacity.Window scaling expands its effective range.
Checksum16 bitsDetects corruption in header and payload.Calculation includes the IP pseudo-header.
Urgent pointer16 bitsPoints to urgent data information.Meaningful when URG is set; rarely used by modern applications.
Options and paddingVariable, within 60-byte maximum headerNegotiates or supplies additional TCP behavior.MSS and window scale are key examples; padding aligns the header.

TCP Control Flags

FlagMeaningTypical use
SYNSynchronize sequence numbers.Begins a connection and carries setup options.
ACKThe acknowledgment field is valid.Confirms received sequence space.
FINThe sender has finished sending.Performs orderly, one-direction closure.
RSTReset the connection immediately.Rejects an invalid connection or closed port.
PSHRequests prompt delivery of buffered data to the application.Provides a push indication; it does not mean a separate packet type.
URGUrgent pointer is meaningful.Marks urgent data; uncommon in modern use.
ECEIndicates ECN-related congestion information.Used when Explicit Congestion Notification is negotiated.
CWRCongestion Window Reduced.Signals response to ECN congestion marking.

MSS, MTU, and Segmentation

Maximum Segment Size (MSS) is the largest TCP payload an endpoint is willing to receive in one segment. MSS excludes the TCP and IP headers. It is commonly negotiated as a TCP option during the handshake.

Maximum Transmission Unit (MTU) is the largest IP packet size supported by a link or path constraint. MSS and MTU are related but not identical: MSS describes TCP payload, while MTU describes the complete IP packet. For a common 1500-byte IPv4 Ethernet MTU, an MSS of 1460 bytes leaves room for a 20-byte IPv4 header and a 20-byte TCP header, assuming no additional headers or options affect the path.

An unsuitable path MTU can cause fragmentation or packet loss. Path MTU Discovery depends in part on ICMP messages that report a packet is too large. If those ICMP messages are blocked, some connections can stall because endpoints do not learn that they must use smaller packets.

TCP Connection Termination

TCP closes each direction independently. An endpoint sends FIN when it has finished sending data, and the peer acknowledges that FIN. The peer can continue sending data in the other direction, which is called a half-close.

A common graceful shutdown therefore uses four messages:

  1. Endpoint A sends FIN.
  2. Endpoint B sends ACK and may continue sending.
  3. Endpoint B later sends FIN.
  4. Endpoint A sends the final ACK.

The endpoint that actively closes commonly enters TIME-WAIT. This state allows delayed segments from the old connection to expire and helps ensure that the final acknowledgment can be retransmitted if necessary before the connection's identifiers are reused.

RST is different from FIN. It abruptly rejects or terminates a connection. A reachable host may send RST when a client connects to a port with no listening service. A reset can also result from an invalid connection or deliberate application or host action. FIN represents orderly closure; RST represents immediate abandonment or rejection.

TCP Connection Lifecycle

PhaseTypical segmentsPurposeRelevant states
EstablishmentSYN, SYN-ACK, ACKCreates state and synchronizes sequence numbers.LISTEN, SYN-SENT, SYN-RECEIVED, ESTABLISHED
Data transferPSH/ACK and data-bearing segments, depending on implementationTransfers an ordered byte stream with acknowledgments and window management.ESTABLISHED
Graceful terminationFIN and ACK in each directionCloses each half of the full-duplex connection.FIN-WAIT, CLOSE-WAIT, LAST-ACK, TIME-WAIT, and related states
Reset or abnormal terminationRSTRejects or immediately aborts a connection.Connection removed or reset

TCP Compared with UDP

CharacteristicTCPUDP
Connection setupConnection-oriented; normally uses a handshake.Connectionless; no TCP-style handshake is required.
Reliability and retransmissionUses acknowledgments and retransmission to provide reliable byte-stream delivery.Provides no built-in delivery guarantee or retransmission.
OrderingReorders data and delivers it as an ordered stream.Does not provide ordered delivery.
Flow and congestion controlProvides receive-window flow control and congestion control.Has no equivalent TCP mechanisms built into the protocol.
Header size20 bytes minimum, up to 60 bytes with options.8 bytes.
Typical application categoriesWeb, secure shell, email transfer, file transfer, and database sessions needing dependable order.Applications prioritizing low overhead or latency, and applications that implement their own reliability.

Practical Example: Opening an HTTPS Session

When a browser connects to a web server, it may select an ephemeral source port such as 49152 and use destination port 443. The client sends SYN, the server replies with SYN-ACK, and the client sends ACK. The four values consisting of both IP addresses and both ports identify the TCP session.

After TCP is established, the endpoints exchange the ordered byte stream used by TLS and HTTPS. TCP segments can be lost or arrive out of order, but TCP acknowledgments, buffering, and retransmission make the stream appear continuous to the higher-layer protocols.

Inspection Commands and Packet Filters

These commands are optional verification tools; no router or switch configuration is required for this conceptual lesson.

# Linux: show TCP listeners and connections
ss -tan

# Alternative on many systems
netstat -an

# Windows PowerShell: test TCP reachability
Test-NetConnection <host> -Port <port>

In a packet analyzer, useful display filters include:

tcp
tcp.port == 443
tcp.flags.syn == 1 && tcp.flags.ack == 0
tcp.flags.reset == 1

Use captures to identify the handshake, sequence and acknowledgment progress, retransmissions, duplicate acknowledgments, zero-window advertisements, FIN-based closure, and RST responses.

TCP Troubleshooting

Connection Times Out During Setup

Common causes include filtering of SYN or SYN-ACK traffic by a firewall or ACL, an incorrect destination address or route, an unavailable server, or a missing return path. Check whether the SYN leaves the client and whether a SYN-ACK returns. A silent drop commonly produces a timeout, whereas an explicit RST indicates a different failure mode.

Connection Is Immediately Refused

A returned RST often means that no service is listening on the destination port or that a host firewall or intermediary actively rejected the connection. Verify the intended port and inspect the server's listener status with a local connection-inspection command.

Transfer Is Slow or Stalls

Look for retransmissions, duplicate acknowledgments, packet loss, increased latency, and a reduced congestion window. Also check whether the advertised receive window is small or zero. Where appropriate, investigate MSS, effective MTU, and possible path MTU discovery problems.

Session Closes Unexpectedly

Identify whether the capture contains FIN or RST. FIN indicates an orderly close, while RST indicates an abrupt reset. Possible causes include an application failure, an intentional reset, or an idle timeout in a firewall, load balancer, or NAT device. Compare the session duration with intermediary timeout settings.

Exam-Relevant Summary

  • TCP is a core TCP/IP protocol at OSI Layer 4.
  • IP delivers between hosts; TCP delivers a reliable stream between applications using ports.
  • A TCP connection is identified by source IP, source port, destination IP, and destination port.
  • The three-way handshake is SYN, SYN-ACK, ACK.
  • Sequence numbers identify byte positions; acknowledgment numbers identify the next byte expected.
  • TCP detects corruption with a checksum and recovers from presumed loss with retransmission.
  • The receive window provides flow control; the congestion window provides congestion control.
  • MSS is TCP payload size; MTU is IP packet size supported by a link or path.
  • FIN performs orderly closure, while RST abruptly resets or rejects a connection.
  • TCP provides more reliability and state than UDP, but with additional overhead and possible latency.