Transmission Control Protocol (TCP)
Learn how TCP establishes connections, delivers reliable ordered data, uses ports and header fields, closes sessions, and supports Nmap TCP scanning.
Transmission Control Protocol (TCP) is a transport-layer protocol in the TCP/IP suite. It lets application processes communicate reliably between different hosts. Web browsing, SSH, email transfer, file transfer, and many database connections commonly use TCP.
This lesson explains TCP's purpose, connection lifecycle, reliability mechanisms, header fields, ports, troubleshooting clues, and relationship to Nmap. For broader context, review the TCP/IP suite of protocols and the OSI model.
TCP's Purpose and Position in Networking
TCP is one of the core protocols in the TCP/IP suite, the family of interoperating protocols used on modern networks. IP provides host-to-host delivery: it moves packets toward an IP address. TCP operates above IP and provides process-to-process delivery between applications.
TCP corresponds to OSI Layer 4, the transport layer. The transport layer is responsible for communication between application processes rather than merely between machines. TCP adds connection management, port numbers, sequencing, acknowledgments, retransmission, flow control, and congestion behavior.
An IP address identifies a host or network interface. A TCP port identifies an application endpoint on that host. Together, an IP address and port identify where a process can receive transport-layer traffic. For example, a browser might connect to a web server at TCP port 443 while using a temporary local source port.
TCP itself is not HTTPS, SSH, HTTP, or a database protocol. It supplies a transport service that those application protocols can use. TLS can then add encryption and authentication, while an application protocol defines requests, responses, and application-level meaning.
Ports, Processes, and the Four-Tuple
A port is a 16-bit TCP identifier ranging from 0 through 65,535. A server commonly binds to a known destination port and listens for incoming connections. A client usually receives an ephemeral source port selected by its operating system.
A particular TCP connection is identified by a four-tuple, also called a socket pair in common usage:
- Source IP address
- Source port
- Destination IP address
- Destination port
For example, a connection could be represented as 192.0.2.20:51544 to 198.51.100.10:443. Multiple clients can connect to the same server port because their source IP addresses or source ports differ.
A listening service has a local socket waiting for new connection attempts. It is not the same as an established connection. After a connection is accepted, the operating system maintains separate state for that connection's four-tuple while the listening socket can continue accepting other clients.
Connection-Oriented Communication
TCP is connection-oriented. Before ordinary application data is exchanged, the endpoints establish shared communication state. This state includes sequence numbers, acknowledgment expectations, receive-window information, negotiated options, and the current lifecycle state.
The endpoint initiating a connection is usually called the client. The endpoint waiting for incoming connections is usually called the server. These are application roles, not permanent properties of a computer: one host can act as a client in one connection and a server in another.
Connection-oriented does not mean that a physical circuit is reserved through every router. TCP state exists at the communicating endpoints, and network devices may also track the flow. IP still forwards individual packets independently.
The Three-Way Handshake
A normal TCP connection begins with a three-way handshake:
- The client sends a segment with the SYN flag set. This announces the client's initial sequence number and requests connection establishment.
- The server responds with SYN and ACK. The server announces its own initial sequence number and acknowledges the client's SYN.
- The client sends an ACK. It acknowledges the server's SYN, completing the normal setup.
Initial sequence numbers establish the starting positions for each direction of the byte stream. The two directions have independent sequence-number spaces. A SYN consumes one sequence-number position even though it carries no application payload.
At a conceptual level, a server begins in LISTEN. An initiating client moves to SYN-SENT after sending SYN. The server's partial connection commonly enters SYN-RECEIVED, and both endpoints reach ESTABLISHED after the final acknowledgment is processed.
A completed handshake indicates that the endpoints exchanged TCP segments successfully in both directions and that each side learned the other's initial sequence information. It does not prove that the application is healthy, authenticated, authorized, fast, or secure.
Opening a Website over HTTPS
A browser might select ephemeral source port 51544 and contact a server at TCP port 443. TCP completes the handshake first. The browser and server then exchange TLS messages, followed by encrypted HTTP traffic. TCP provides the ordered transport; TLS provides cryptographic protection; HTTP provides web semantics.
Reliable, Ordered Byte-Stream Delivery
TCP presents an application with a reliable, ordered byte stream. It does not preserve application message boundaries. If an application writes two blocks of data, the receiving application reads a stream and may receive those bytes in different-sized reads. The application protocol must define its own message boundaries.
Sequence numbers mark byte positions in the stream. If a segment carries bytes beginning at sequence number 10,000 and contains 1,000 bytes, the next byte is numbered 11,000. The acknowledgment number normally identifies the next byte the receiver expects.
An acknowledgment of 11,000 means that all bytes before 11,000 have been received in order and that byte 11,000 is the next expected byte. Acknowledgments do not necessarily correspond one-for-one with individual segments.
Loss, Retransmission, and Reordering
If a data segment or acknowledgment is lost, the sender can retransmit data. TCP infers loss through mechanisms such as retransmission timers and repeated acknowledgments. The exact algorithms are implementation-dependent, but the goal is to recover missing bytes without exposing a gap to the receiving application.
Segments can arrive out of order because packets take different paths through a network or experience different delays. TCP can retain out-of-order data, acknowledge what is appropriate, and reassemble the stream before delivering a contiguous sequence to the application.
Consider a file transfer in which segments containing bytes 0–999, 1,000–1,999, and 2,000–2,999 are sent. If the middle segment is lost, the receiver cannot advance its cumulative acknowledgment past byte 1,000, even if the later segment arrives. The sender eventually retransmits the missing range. The application ultimately receives one ordered stream rather than a visible hole.
Flow Control and Congestion Behavior
Flow control protects the receiver. A receiver advertises a receive window, which tells the sender how much additional unacknowledged data the receiver can accept. The sender limits data in flight so it does not overwhelm the receiver's buffers.
Window scaling is a negotiated TCP option that permits a much larger effective receive window than the basic window field alone can represent. This is especially useful on paths with high bandwidth, long round-trip times, or both.
Flow control and congestion control solve different problems. Flow control responds to the receiving host's available capacity. Congestion control responds to conditions in the network path. TCP adjusts its sending behavior when it infers loss, excessive delay, or congestion, reducing or pacing traffic and then probing for available capacity according to its congestion-control algorithm.
These mechanisms require additional state, timers, acknowledgments, and processing. Consequently, TCP has more overhead and more behavior than a lightweight datagram protocol such as UDP. The added complexity is useful when reliable delivery matters.
TCP Segments and Header Fields
TCP data is carried in segments. A segment contains a TCP header and, optionally, application payload. The segment is carried inside an IP packet.
The standard TCP header is at least 20 bytes. Options can expand the header to a maximum of 60 bytes. The data-offset field tells the receiver where the payload begins, which is necessary when options are present.
Common TCP Options
- Maximum Segment Size (MSS): Communicates the largest TCP payload segment an endpoint is prepared to receive. MSS excludes the TCP and IP headers.
- Window Scale: Expands the effective receive-window range.
- Selective Acknowledgment (SACK): Lets a receiver identify noncontiguous blocks that arrived, helping the sender retransmit only missing ranges.
- Timestamps: Help with timing measurements and protection against some sequence-number ambiguity.
The TCP checksum is an integrity check, not encryption and not authentication. A valid checksum indicates that corruption was not detected by that check; it does not prove that the sender is trusted.
Connection Termination and Reset Behavior
TCP closes gracefully with FIN and ACK exchanges. A FIN means that an endpoint has no more data to send in one direction. Because each direction is independent, one endpoint can send FIN while still receiving data from its peer. This is sometimes called a half-close.
A typical orderly close is:
- One endpoint sends FIN.
- The peer acknowledges the FIN and may continue sending remaining data.
- The peer later sends its own FIN.
- The first endpoint acknowledges that FIN.
The exact state names depend on which endpoint starts the close. States commonly encountered include FIN-WAIT-1, FIN-WAIT-2, CLOSE-WAIT, LAST-ACK, and TIME-WAIT.
TIME-WAIT is retained after an active close. It gives delayed segments from the earlier connection time to expire and helps ensure that a new connection reusing the same four-tuple is not confused by old traffic.
RST is an abrupt reset. It can reject an incoming attempt, terminate a connection for which no valid state exists, or signal that a segment does not match the receiver's expectations. Unlike FIN, RST does not provide orderly delivery of remaining application data.
Gracefully Ending an SSH Session
When one side of an SSH session has no more data to send, it can send FIN. The other side acknowledges the FIN and may still transmit its remaining output before sending its own FIN. A packet trace can therefore show one direction closed before the entire TCP connection ends.
TCP Services and Port Ranges
Common TCP-based application protocols include HTTP and HTTPS, SSH, SMTP, FTP, and many database services. TCP is not tied to any one of them; any application protocol can be designed to use TCP.
- Well-known ports: 0–1,023. These are traditionally associated with core and widely used services.
- Registered ports: 1,024–49,151. Applications and vendors commonly register or use ports in this range.
- Dynamic or ephemeral ports: 49,152–65,535 in the commonly taught IANA range. Operating systems select ephemeral ports for short-lived client-side connections, although exact local allocation policies vary.
Conventional port numbers are clues, not proof. HTTPS commonly uses TCP 443 and SSH commonly uses TCP 22, but administrators can configure services to use other ports. Conversely, a process listening on a familiar port is not automatically the expected application. Service detection is needed to identify what is actually operating.
See TCP and UDP ports for more port fundamentals.
TCP in Nmap
TCP service discovery commonly depends on observing responses to control flags and connection attempts. A scanner sends a probe to a target port and interprets responses in the context of TCP behavior, filtering, routing, and the scan technique.
TCP Connect and SYN-Based Scans
A TCP connect scan asks the operating system to perform a normal connection. When the handshake completes, the scanner knows that the target accepted a TCP connection attempt. Nmap's -sT option requests this style of scan.
A SYN scan sends a SYN and examines the reply without completing a normal application connection in the usual case. A SYN-ACK generally indicates that a service is listening. The scanner then prevents the connection from becoming a normal established session, commonly by sending RST. Nmap's -sS option requests a SYN-based scan and may require elevated privileges.
An RST commonly indicates that no service is listening on the destination port. However, firewalls, intrusion-prevention systems, proxies, rate limits, packet loss, and unusual implementations can alter the observed behavior.
Nmap's labels such as open, closed, and filtered summarize observations rather than providing an absolute view of the target's internal state. Learn more in Nmap port states and interpreting scan results.
Only scan systems and networks for which you have explicit authorization and a defined scope. Avoid scanning arbitrary public targets. Start with a small, approved port set and appropriate timing.
nmap -sT -p 22,80,443 <authorized-target>This demonstrates a TCP connect scan using the operating system's normal connection process.
nmap -sS -p 22,80,443 <authorized-target>This demonstrates SYN-based TCP port discovery. Firewalls, packet filters, and rate limiting can affect the results.
nmap -sV -p 22,80,443 <authorized-target>Service/version detection sends additional probes to identify the application behind an open port. Finding an open TCP port and identifying the service are separate tasks. Use -sV only within an approved scope.
ss -tanOn many Linux systems, this displays local TCP sockets, including listening and established states. It is useful for connecting TCP state names to real local processes and connections.
Related practical material includes TCP SYN host discovery, service version detection, and Nmap packet tracing.
TCP Connection Lifecycle
TCP Compared with UDP
UDP is also a transport-layer protocol, but it provides connectionless datagrams. It does not perform TCP's three-way handshake and does not inherently provide ordered delivery, retransmission, receiver flow control, or TCP-style congestion control.
Troubleshooting TCP Behavior
A Connection Attempt Times Out
Possible causes include a firewall silently dropping packets, an unavailable host or route, a stateful device dropping unsolicited traffic, congestion, or packet loss. A timeout alone does not establish that a port is closed. A closed TCP port commonly responds with RST, while filtering often produces no response.
A Connection Is Immediately Refused
The host may be reachable but have no service listening on the destination port. A local or intermediary policy may also actively reject the attempt. A TCP RST is the usual network-level signal associated with rejection or a closed port, but implementations and middleboxes vary.
An Established Transfer Is Slow
Investigate packet loss and retransmissions, a small advertised receive window, high round-trip time, path congestion, server limits, and application processing. Successful handshake completion proves basic two-way reachability, not high throughput or healthy application behavior.
A Connection Closes Unexpectedly
Look for the difference between FIN and RST in a packet trace. FIN indicates an orderly directional shutdown. RST indicates an abrupt reset and may occur because an endpoint lacks matching connection state, an application terminated the session, or a firewall or network device expired state.
Exam-Relevant Summary
- TCP is a transport-layer protocol corresponding to OSI Layer 4.
- IP addresses identify hosts; TCP ports identify application endpoints on those hosts.
- A TCP connection is identified by source IP, source port, destination IP, and destination port.
- The normal handshake is SYN, SYN-ACK, and ACK.
- TCP provides a reliable, ordered byte stream using sequence numbers, acknowledgments, retransmission, and reassembly.
- The receive window provides flow control; congestion control responds to network conditions.
- A TCP header is at least 20 bytes and can be up to 60 bytes with options.
- Important flags include SYN, ACK, FIN, RST, PSH, and URG; ECE and CWR support ECN signaling.
- FIN supports orderly, directional closure; TIME-WAIT helps protect connection reuse; RST is an abrupt reset.
- A SYN-ACK generally suggests an open listening service, an RST commonly suggests a closed port, and no response often suggests filtering or loss but is not conclusive.
- TCP and UDP serve different application requirements; reliability is not the only design goal.