CCNA 200-301

CCNP Enterprise

CCNP Security

CCIE Enterprise Lab

CCIE Security Lab

CCNP Service Provider

CCNP Data Center

CCNP Collaboration

CCIE DC Lab

Every web page load, video call, multiplayer match, and DNS lookup relies on two foundational protocols to move data between applications: the Transmission Control Protocol (TCP) and the User Datagram Protocol (UDP). While the Internet Protocol (IP) handles addressing and routing packets from one machine to another, TCP and UDP decide how application data is packaged, delivered, and verified once it reaches the target host. Understanding how both protocols operate—and why networks still need a strict reliability workhorse alongside a lightweight speed specialist—is essential for building, administering, and troubleshooting modern systems.

How TCP and UDP Work at the OSI Transport Layer

TCP and UDP operate at Layer 4 (the Transport Layer) of the OSI model (and the equivalent Transport layer of the TCP/IP suite). Whereas Layer 3 (Network/IP) only cares about moving packets between source and destination IP addresses, Layer 4 enables process-to-process communication by attaching source and destination port numbers so a single device can run dozens of network services simultaneously. Despite sharing that role, TCP and UDP move data through fundamentally different workflows.

How TCP Establishes and Manages Connections

TCP is a connection-oriented, stateful protocol. Before transmitting a single byte of application payload, both endpoints negotiate an active session and agree on tracking parameters through a sequential lifecycle:

  1. Session Setup via the Three-Way Handshake:
  2. Step 1 (SYN): The client sends a synchronize segment containing its initial sequence number (ISN) to request a connection.
  3. Step 2 (SYN-ACK): The server allocates session buffers, replies with its own initial sequence number, and acknowledges the client’s SYN.
  4. Step 3 (ACK): The client acknowledges the server’s response, establishing a full-duplex virtual connection ready for payload transfer.
  5. Segmented and Tracked Data Transfer: TCP slices application streams into numbered segments. As segments arrive, the receiver returns acknowledgment (ACK) numbers indicating the next expected byte. If a timer expires before an ACK arrives, the sender automatically retransmits the missing segment, while the receiver reassembles out-of-order segments into the exact byte sequence sent.
  6. Graceful Connection Teardown: When communication finishes, both sides close their half of the stream using a four-step FIN and ACK exchange (or terminate abruptly with a RST segment if an error occurs), freeing kernel state on both hosts.

How UDP Transmits Connectionless Datagrams

UDP is a connectionless, stateless protocol designed around minimal protocol mechanics rather than session guarantees:

  1. Direct Datagram Encapsulation: The sending application passes a discrete message buffer to UDP, which prepends a compact header containing source port, destination port, message length, and checksum to form a datagram.
  2. Immediate Fire-and-Forget Transmission: UDP hands the datagram directly to the IP layer with zero prior handshake, connection state, or receiver readiness check.
  3. Independent Delivery: Each datagram travels across the network independently. The receiving OS validates the checksum (discarding corrupted packets silently) and queues intact datagrams for the target port in whatever order they arrive, without sending transport-layer acknowledgments or requesting retransmissions.

In short, TCP trades setup time and state tracking for a guaranteed, ordered byte stream, whereas UDP strips Layer 4 down to bare port multiplexing and integrity checking.

TCP vs. UDP: Speed, Reliability, and Header Overhead

Those architectural mechanics directly shape how both protocols perform on the wire. Comparing TCP and UDP side-by-side highlights the exact engineering trade-offs behind transfer latency, packet overhead, and fault recovery.

Technical CriterionTCP (Transmission Control Protocol)UDP (User Datagram Protocol)
Connection ModelConnection-oriented (requires 3-way handshake before payload)Connectionless (zero setup; transmits immediately)
Layer 4 Data UnitSegmentDatagram
Header Size20–60 bytes (20-byte base header plus up to 40 bytes of options)8 bytes fixed (Source Port, Dest Port, Length, Checksum—2 bytes each)
Transfer Speed & LatencyHigher latency due to handshake RTT, ACK processing, and retransmission stallsLowest transport latency; no handshake delay or retransmission stalls
ReliabilityGuaranteed delivery via ACKs, timeouts, and automatic retransmissionBest-effort delivery; lost packets are not recovered by Layer 4
Packet OrderingStrict in-order delivery enforced via 32-bit sequence numbersUnordered; datagrams may arrive out of sequence or be duplicated
Error CheckingMandatory 16-bit checksum; corrupted segments trigger retransmission16-bit checksum (optional in IPv4, mandatory in IPv6); bad frames dropped
Flow ControlSliding window (rwnd) prevents fast senders from overwhelming slow receiversNone; applications must pace their own send rates
Congestion ControlBuilt-in algorithms (e.g., CUBIC, BBR) throttle sending rates during network congestionNone at the transport layer
Addressing ModesUnicast (one-to-one) onlyUnicast, Multicast (one-to-many), and Broadcast (one-to-all)

Why UDP Is Faster Than TCP

UDP achieves lower latency not because its bits travel faster across fiber or copper, but because it eliminates waiting. TCP incurs a full round-trip time (RTT) during its initial handshake and stalls upper-layer reads whenever a dropped packet forces the OS kernel to wait for a retransmission before releasing subsequent in-order bytes. Combined with an 8-byte header that is at least 60% smaller than TCP’s base header, UDP maximizes raw packet rate and responsiveness—leaving reliability completely optional for the application layer to customize or skip.

When to Use TCP vs. UDP for Gaming, Streaming, VoIP, and Web Traffic

Choosing the right transport protocol comes down to answering one core question about your workload: is late data better than missing data, or is late data useless? Walking through three practical workload profiles makes protocol selection straightforward.

1. Choose TCP When Every Byte Must Arrive Intact

If a single dropped or reordered byte corrupts a document, breaks code execution, or alters a financial ledger, retransmission delays are well worth paying:

  • Web Browsing and REST APIs (HTTP/1.1, HTTP/2): HTML, CSS, JavaScript bundles, and JSON responses cannot render or parse reliably if fragments go missing. (Modern HTTP/3 is a notable exception covered later.)
  • File Transfers and Email (FTP, SFTP, SMB, SMTP, IMAP): A downloaded archive or email attachment with a missing 1,400-byte chunk is corrupted and unusable.
  • Remote Administration and Databases (SSH, PostgreSQL, MySQL): Interactive terminal commands and SQL transactions require strict command ordering and persistent session state.

2. Choose UDP When Real-Time Timeliness Beats Perfect Delivery

In live interactive applications, waiting 150 milliseconds to retransmit an old packet freezes the user experience for data whose moment has already passed:

  • Fast-Paced Multiplayer Gaming: First-person shooters and racing simulators broadcast player coordinates and input ticks 30 to 128 times per second. If tick #42 drops on the wire, retransmitting it is pointless because tick #43 is already arriving with fresher coordinates. Games use UDP for real-time world state and reserve TCP (or selective application-level ACKs over UDP) for chat messages and inventory purchases.
  • VoIP and Video Conferencing (WebRTC, RTP/SRTP): During a live voice or video call, a dropped UDP audio frame produces a barely perceptible 10–20 ms micro-glitch concealed by codec interpolation, whereas TCP’s retransmission and congestion backoff would cause jarring multi-second audio freezes.
  • Live vs. On-Demand Video Streaming: Ultra-low-latency live broadcasts (sports feeds, cloud gaming, drone telemetry via RTP, WebRTC, or SRT) run over UDP to stay within sub-second glass-to-glass targets. By contrast, on-demand video platforms like Netflix or YouTube VOD primarily use HTTP over TCP (or QUIC) because the player maintains a multi-second playback buffer, giving TCP plenty of time to retransmit lost segments invisibly.

3. Choose UDP for Single-Packet Queries and Broadcast Discovery

When an entire request and response fit inside single packets, TCP’s 3-way handshake and 4-way teardown add more control packets than actual payload:

  • DNS Lookups: Standard domain name queries use UDP to resolve addresses in a single round trip, falling back to TCP only for zone transfers (AXFR) or large DNSSEC responses that exceed negotiated datagram limits.
  • Local Network Bootstrapping and Time Sync (DHCP, NTP): A newly connected client has no IP address yet and must broadcast discovery frames across the subnet—something point-to-point TCP cannot do—while NTP uses UDP to measure network transit times without TCP retransmission skewing clock calculations.

Common TCP and UDP Port Numbers Cheat Sheet

Every network service above listens on standardized Layer 4 port numbers assigned by IANA so operating systems can route incoming segments and datagrams to the right process. You can copy, save, or print the reference sheet below directly to PDF for network administration or certification prep (CompTIA Network+, Security+, and Cisco CCNA).

==============================================================================
                 TCP & UDP WELL-KNOWN PORTS QUICK REFERENCE
==============================================================================
IANA PORT RANGES
  0 - 1023        Well-Known Ports (System / privileged network services)
  1024 - 49151    Registered Ports (Vendor & user applications)
  49152 - 65535   Dynamic / Ephemeral Ports (Temporary client source ports)
------------------------------------------------------------------------------
PORT(S)      PROTOCOL    SERVICE     COMMON USAGE / NOTES
------------------------------------------------------------------------------
20 / 21      TCP         FTP         File Transfer (20: Data, 21: Control)
22           TCP         SSH / SFTP  Encrypted remote CLI & file transfer
23           TCP         Telnet      Legacy unencrypted remote terminal
25           TCP         SMTP        Server-to-server email routing
53           TCP / UDP   DNS         UDP: Standard lookups | TCP: Zone xfers
67 / 68      UDP         DHCP        Dynamic IP assignment (67: Srv, 68: Cli)
69           UDP         TFTP        Lightweight, unauthenticated file xfer
80           TCP         HTTP        Unencrypted web traffic
110          TCP         POP3        Legacy mail retrieval
123          UDP         NTP         Clock & time synchronization
143          TCP         IMAP        Email mailbox synchronization
161 / 162    UDP         SNMP        Network monitoring (161: Poll, 162: Trap)
389          TCP / UDP   LDAP        Directory services queries
443          TCP / UDP   HTTPS       TCP: HTTP/1.1 & H2 | UDP: HTTP/3 (QUIC)
445          TCP         SMB         Windows file & printer sharing
500 / 4500   UDP         IKE / IPsec VPN key exchange & NAT traversal
514          UDP         Syslog      Standard system event logging
587          TCP         SMTP (TLS)  Authenticated client mail submission
993 / 995    TCP         IMAPS/POP3S TLS-encrypted IMAP (993) & POP3 (995)
1194         TCP / UDP   OpenVPN     SSL/TLS VPN tunnel (UDP recommended)
3306         TCP         MySQL       MySQL / MariaDB database connections
3389         TCP / UDP   RDP         Remote Desktop (TCP core + UDP transport)
5060 / 5061  TCP / UDP   SIP         VoIP call signaling (5061: TLS over TCP)
51820        UDP         WireGuard   Modern encrypted VPN tunnel
==============================================================================

Notice that dual-stack entries such as 53, 443, and 3389 do not share a single socket—TCP port 53 and UDP port 53 are completely separate Layer 4 namespaces that can bind independently on the same IP address.

TCP and UDP Socket Programming Examples in Python

When building custom networked software, developers choose between TCP and UDP through the operating system’s socket API—specifically SOCK_STREAM for byte-stream TCP connections and SOCK_DGRAM for message-oriented UDP datagrams. The runnable Python 3 templates below demonstrate both client-server patterns using standard library context managers.

TCP Client and Server (SOCK_STREAM)

# --- tcp_server.py ---
import socket

HOST, PORT = "127.0.0.1", 65432

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as server:
    server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    server.bind((HOST, PORT))
    server.listen()
    conn, client_addr = server.accept()  # Blocks until 3-way handshake completes
    with conn:
        payload = conn.recv(1024)
        conn.sendall(b"ACK: " + payload)
# --- tcp_client.py ---
import socket

HOST, PORT = "127.0.0.1", 65432

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as client:
    client.connect((HOST, PORT))         # Initiates TCP handshake
    client.sendall(b"Stream payload")
    reply = client.recv(1024)
    print(reply.decode("utf-8"))

UDP Client and Server (SOCK_DGRAM)

# --- udp_server.py ---
import socket

HOST, PORT = "127.0.0.1", 65433

with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as server:
    server.bind((HOST, PORT))            # No listen() or accept() needed
    payload, client_addr = server.recvfrom(1024)
    server.sendto(b"ECHO: " + payload, client_addr)
# --- udp_client.py ---
import socket

HOST, PORT = "127.0.0.1", 65433

with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as client:
    client.settimeout(3.0)               # Prevent infinite block if packet drops
    client.sendto(b"Datagram payload", (HOST, PORT))
    reply, _ = client.recvfrom(1024)
    print(reply.decode("utf-8"))

The structural difference in code mirrors the wire behavior: TCP’s accept() spawns a dedicated socket bound to a single connected peer, whereas a single UDP socket receives datagrams from any number of clients via recvfrom() and addresses each reply explicitly.

How to Check Open TCP and UDP Ports and Active Connections

Once standard services or custom socket applications are deployed, administrators use built-in command-line utilities to verify local bindings, test remote firewall paths, and isolate packet loss. Follow this three-step diagnostic workflow across Linux, Windows, and macOS.

Step 1: Inspect Local Listening Ports and Active Sessions

Start on the host itself to confirm that the process is bound to the expected interface and protocol:

  • Linux (ss): Run sudo ss -tulnp (-t TCP, -u UDP, -l listening, -n numeric ports, -p process ID/name). Active TCP sockets display stateful stages such as LISTEN or ESTAB, whereas listening UDP sockets show UNCONN because, as covered earlier, UDP maintains no session state. To see established TCP sessions too, omit -l (sudo ss -tunp).
  • Windows (CMD / PowerShell): Run netstat -ano to view all TCP states, stateless UDP endpoints, and owning PIDs, or use PowerShell’s structured cmdlets: Get-NetTCPConnection -State Listen,Established and Get-NetUDPEndpoint.
  • macOS (lsof): Run sudo lsof -iTCP -sTCP:LISTEN -P -n to inspect listening TCP services and sudo lsof -iUDP -P -n to list active UDP bindings alongside process names.

Step 2: Test Remote Port Reachability Across the Network

If a service is listening locally but clients cannot connect, probe the remote port from another machine to rule out host firewalls or security groups:

  • Testing TCP Reachability: On Linux and macOS, run nc -zv <target_host> 443. On Windows PowerShell, run Test-NetConnection -ComputerName <target_host> -Port 443. Because TCP performs a handshake, a SYN-ACK response gives a definitive confirmation that the port is open and reachable.
  • Testing UDP Reachability: Run nc -zvu <target_host> 53 (or sudo nmap -sU -p 53 <target_host>). Interpret UDP results carefully: with no handshake, nc assumes a port is open whenever it does not receive an ICMP Port Unreachable error—meaning a firewall that silently drops packets can look identical to an open port. The most reliable UDP test is sending a real application query (such as dig @<target_host> example.com for DNS) and verifying a valid payload response.

Step 3: Measure Throughput, Retransmissions, and UDP Packet Loss

When connectivity works but performance degrades, run iperf3 between two endpoints (iperf3 -s on the receiver):

  • TCP test: iperf3 -c <server_ip> measures achievable bandwidth and reports exact TCP Retr (retransmission) counts.
  • UDP test: iperf3 -c <server_ip> -u -b 100M sends a constant 100 Mbps datagram stream and reports exact jitter (ms) and lost/total datagram percentages—key metrics for diagnosing VoIP and gaming lag.

When port checks and synthetic benchmarks point to mid-path drops or erratic delays, deeper packet-level visibility becomes necessary.

Best Packet Sniffers and Monitoring Tools for TCP and UDP Traffic

Capturing and decoding live traffic lets engineers see exact TCP sequence numbers, window scaling bottlenecks, and raw UDP payloads on the wire. Here are five widely adopted packet analyzers and network monitors suited to different operational environments:

  1. Wireshark (Best for Interactive GUI Protocol Dissection): The industry-standard open-source graphical analyzer decodes hundreds of protocols atop TCP and UDP. Its built-in expert analysis flags TCP retransmissions, duplicate ACKs, out-of-order segments, and zero-window stalls automatically, while Follow TCP Stream and Follow UDP Stream reconstruct full application conversations in clicks.
  2. tcpdump (Best for Headless CLI Packet Capture): Built on libpcap and available across Linux, BSD, and macOS, tcpdump captures live frames directly over SSH with minimal CPU overhead. Administrators routinely filter specific transport flows—such as sudo tcpdump -nn -i eth0 'tcp port 443 or udp port 53' -w trace.pcap—and export the .pcap file for visual inspection in Wireshark.
  3. TShark (Best for Scripted and Automated Diagnostics): As Wireshark’s official command-line counterpart, TShark brings full Wireshark display filters (for example, tshark -r trace.pcap -Y "tcp.analysis.retransmission") to terminal pipelines, cron jobs, and automated CI/CD network test suites.
  4. Zeek (Best for Continuous Connection Telemetry and Security Auditing): Rather than storing multi-terabit raw packet captures, Zeek passively inspects wire traffic and writes structured transaction logs. Its conn.log summarizes every TCP handshake, byte count, termination state, and UDP pseudo-flow, making long-term anomaly hunting fast and searchable.
  5. Paessler PRTG / SolarWinds Network Performance Monitor (Best for Enterprise Flow Dashboards): For fleet-wide visibility across routers, switches, and WAN links, commercial monitoring platforms ingest NetFlow, sFlow, and IPFIX telemetry to chart aggregate TCP vs. UDP bandwidth utilization, top talkers by port, and VoIP UDP jitter SLA thresholds in real time.

Anyone inspecting modern HTTPS sessions in Wireshark or Zeek quickly notices a striking trend: a massive share of encrypted web traffic on port 443 now runs over UDP rather than TCP.

How HTTP/3 and QUIC Use UDP in Modern Web Networking

For over three decades, HTTP relied exclusively on TCP for reliable web transport. The rollout of QUIC and HTTP/3 changed that architecture by shifting web transport onto UDP—raising common questions about how modern web networking works.

Why did HTTP/3 switch from TCP to UDP?

HTTP/2 introduced stream multiplexing so browsers could fetch dozens of images, scripts, and API responses over a single TCP connection. However, that created transport-layer head-of-line (HOL) blocking: because the OS kernel’s TCP stack views the entire connection as one strictly ordered byte stream, a single lost packet stalls every active HTTP/2 stream until TCP retransmits that missing segment. Furthermore, deploying a brand-new Layer 4 protocol directly atop IP is practically impossible on the public internet because legacy firewalls, NAT gateways, and carrier middleboxes drop unfamiliar protocol numbers—an issue known as protocol ossification. Wrapping the new transport inside standard UDP datagrams ensured immediate compatibility through existing network hardware.

How does QUIC make UDP reliable?

Defined in IETF RFC 9000 (with HTTP/3 specified in RFC 9114), QUIC runs in user space on top of UDP and implements its own packet acknowledgments, loss recovery, flow control, and congestion control per stream rather than per connection:

  • Zero Transport Head-of-Line Blocking: Each HTTP/3 asset travels in an independent QUIC stream. If a UDP packet carrying Stream A drops, QUIC retransmits only that stream’s data while Streams B, C, and D keep delivering bytes to the browser immediately.
  • Faster Encrypted Handshakes: Instead of completing a TCP handshake and then a separate TLS handshake (2 to 3 RTTs total), QUIC embeds TLS 1.3 cryptographic negotiation directly into its initial packet exchange—establishing an encrypted session in 1-RTT, or 0-RTT when resuming a known connection.
  • Seamless Network Migration: Traditional TCP connections are bound to a four-tuple (source IP, source port, destination IP, destination port), breaking whenever a phone switches from Wi-Fi to 5G. QUIC identifies sessions via a Connection ID, allowing active streams to survive IP and port changes without re-handshaking.

Is QUIC over UDP completely replacing TCP?

No. While HTTP/3 over QUIC carries a substantial share of global browser, CDN, and mobile app traffic, TCP remains indispensable. Many enterprise firewalls still block or rate-limit UDP port 443 (prompting browsers to fall back seamlessly to HTTP/2 over TCP), data center NICs provide mature hardware offload (TSO/LRO) that makes kernel TCP remarkably CPU-efficient for east-west server traffic, and core protocols like SSH, SMTP, and relational database wire protocols continue to rely on OS-managed TCP stacks without needing user-space multiplexing.

Official IETF RFC Specifications for TCP and UDP

Engineers implementing protocol stacks, writing firewall parsers, or auditing compliance should consult the canonical Internet Engineering Task Force (IETF) standards documents that formally define TCP and UDP.

Transmission Control Protocol (TCP) — Internet Standard STD 7

  • Primary Specification: RFC 9293 (Transmission Control Protocol (TCP), edited by W. Eddy, published August 2022). Canonical URL: https://datatracker.ietf.org/doc/html/rfc9293
  • Standards Lineage: RFC 9293 formally obsoletes the original 1981 specification (RFC 793) along with RFC 879, RFC 2873, RFC 6093, RFC 6429, RFC 6528, and RFC 6691, and updates RFC 1011, RFC 1122, and RFC 5961. It consolidates over forty years of protocol errata, state-machine clarifications, and security mitigations into a single authoritative specification.
  • Core Companion RFCs: RFC 5681 (defines standard TCP congestion control mechanisms: slow start, congestion avoidance, fast retransmit, and fast recovery) and RFC 7323 (specifies TCP extensions for high-performance networks, including Window Scale and Timestamps).

User Datagram Protocol (UDP) — Internet Standard STD 6

  • Primary Specification: RFC 768 (User Datagram Protocol, authored by J. Postel, published August 1980). Canonical URL: https://datatracker.ietf.org/doc/html/rfc768
  • Standards Lineage: RFC 768 remains the active, unmodified core specification defining the 8-byte UDP header layout, port multiplexing fields, and IP pseudo-header checksum calculation.
  • Core Companion RFC: RFC 8085 / BCP 145 (UDP Usage Guidelines, edited by L. Eggert, G. Fairhurst, and G. Shepherd, published March 2017; obsoletes RFC 5405). Defines current best practices for applications building custom protocols over UDP, including congestion control requirements, path MTU sizing, and IPv4/IPv6 checksum enforcement.

Conclusion

TCP and UDP endure as the twin pillars of Transport Layer networking because they solve opposite halves of the communication problem. TCP shoulders the complexity of connection setup, sequencing, flow regulation, and guaranteed recovery so applications can treat the network as a dependable byte stream. UDP strips transport overhead down to bare port addressing and integrity checks, delivering both the raw speed required by real-time audio, video, and multiplayer gaming and the flexible substrate powering modern protocols like QUIC and HTTP/3. Mastering when to deploy each protocol—and how to code against, test, and inspect them on the wire—gives you a durable foundation for working with virtually any networked system.

Please follow and like us:
Last modified: December 3, 2026

Author

Comments

Write a Reply or Comment

Your email address will not be published.