> For the complete documentation index, see [llms.txt](https://naz.gitbook.io/my-docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://naz.gitbook.io/my-docs/basic-networking/tcp_and_udp_ccna_day30.md).

# TCP and UDP

## Introduction

This video covers two very important Layer 4 protocols: TCP (Transmission Control Protocol) and UDP (User Datagram Protocol). These appear in CCNA exam topic 1.5, which says you must be able to compare TCP to UDP. You don't need hours of detailed mechanics -- for the CCNA, you need a high-level understanding of their basic characteristics and how they differ.

## Basics of Layer 4

We've covered Layers 1, 2, and 3 already. At Layer 1 we covered cable types. At Layer 2 we covered MAC addresses, switching, and spanning tree. At Layer 3 we covered IP addresses and routing. Now is a good time to talk about Layer 4.

```mermaid
flowchart TB
    subgraph Layers["The 5-Layer Model"]
        direction TB
        L5["5 Application<br/>HTTP, FTP, DNS"]
        L4["4 Transport<br/>TCP, UDP"]
        L3["3 Internet<br/>IP addresses, routing"]
        L2["2 Local Network<br/>MAC addresses, switching"]
        L1["1 Physical<br/>Cables, signals"]
    end

    L5 --> L4 --> L3 --> L2 --> L1
```

### Transparent Transfer of Data

Layer 4 provides transparent transfer of data between end hosts. Host A sends data to Host B. The Transport Layer encapsulates the data with a Layer 4 header, then uses the services of the lower layers (3, 2, and 1) to deliver the data unchanged to the destination host. The hosts themselves are not aware of the details of the underlying network -- the transfer of data is "transparent" to them.

```mermaid
sequenceDiagram
    participant HostA as Host A
    participant L3_1 as L3, L2, L1
    participant L3_2 as L3, L2, L1
    participant HostB as Host B

    HostA->>L3_1: data + L4 header
    L3_1->>L3_2: delivered across network
    L3_2->>HostB: data delivered unchanged

    Note over HostA,HostB: Hosts do not see underlying network details
```

### Services That Layer 4 Can Provide

Layer 4 protocols can provide (or not provide) various services to applications. TCP provides these services, UDP does not:

* **Reliable data transfer** -- making sure the destination host actually received every bit of data
* **Error recovery** -- if an error occurs in transmission, Layer 4 can ensure the data is sent again
* **Data sequencing** -- making sure that even if data arrives out of order, the end host can sequence it correctly
* **Flow control** -- making sure the source host does not send traffic faster than the destination host can handle

## Port Numbers and Session Multiplexing

Layer 4 provides Layer 4 addressing called **port numbers**. Note that the word "port" can also refer to physical interfaces on network devices, but the Layer 4 port is a totally different meaning.

Port numbers provide two functions:

* Identifying the Application Layer protocol being used
* Providing **session multiplexing**

### What Is a Session?

A session is simply an exchange of data between two or more communicating devices. Your PC handles multiple sessions at once -- multiple browser tabs, multiple services needing Internet access.

### How Ports Work

PC1 accesses resources from two servers over the Internet, SRV1 and SRV2.

PC1 communicates with SRV1 using TCP. The source port is 50000 (randomly selected) and the destination port is 80 (HTTP). The destination port identifies the Application Layer protocol -- TCP port 80 is HTTP, used to access websites.

SRV1 replies with the port numbers reversed: source port 80, destination port 50000. When PC1 receives this, the port numbers tell it this is part of the same session.

```mermaid
sequenceDiagram
    participant PC1 as PC1
    participant SRV1 as SRV1

    PC1->>SRV1: src 50000 -> dst 80 (HTTP)
    SRV1->>PC1: src 80 -> dst 50000
    Note over PC1,SRV1: Same session identified by port pair
```

If PC1 opens a separate connection to SRV1, it uses a different source port but the same destination port 80. SRV1's response uses that new source port as its destination, so PC1 knows it is a different session.

```mermaid
sequenceDiagram
    participant PC1 as PC1
    participant SRV1 as SRV1

    PC1->>SRV1: src 50000 -> dst 80 (HTTP session 1)
    SRV1->>PC1: src 80 -> dst 50000
    PC1->>SRV1: src 50001 -> dst 80 (HTTP session 2)
    SRV1->>PC1: src 80 -> dst 50001
    Note over PC1,SRV1: Different sessions, same server, same dest port
```

PC1 also wants to access SRV2 at the same time. It uses destination port 21 (FTP) and randomly selects source port 60000. SRV2's reply reverses the ports: source 21, destination 60000.

```mermaid
sequenceDiagram
    participant PC1 as PC1
    participant SRV2 as SRV2

    PC1->>SRV2: src 60000 -> dst 21 (FTP)
    SRV2->>PC1: src 21 -> dst 60000
    Note over PC1,SRV2: FTP session to a different server
```

### IANA Port Number Ranges

Port numbers that Application Layer protocols use are registered with IANA (Internet Assigned Numbers Authority). Three ranges:

| Range         | Name       | Purpose                                                   |
| ------------- | ---------- | --------------------------------------------------------- |
| 0 - 1023      | Well-known | Major protocols like HTTP, FTP, strictly regulated        |
| 1024 - 49151  | Registered | Registration required, less strict                        |
| 49152 - 65535 | Ephemeral  | Private or dynamic, hosts select randomly for source port |

In the previous examples, all randomly selected source ports came from the ephemeral port range (50000, 50001, 60000).

Both TCP and UDP use port numbers. Port numbers are a function of both main Layer 4 protocols.

## TCP Overview

TCP (Transmission Control Protocol) provides services that UDP does not. Here is an overview of TCP's key characteristics:

### Connection-Oriented

Before actually sending data to the destination host, the two hosts communicate to establish a connection. Once the connection is established, the data exchange begins. The source host does not just start sending data without first communicating with the destination host.

### Reliable Communication

The destination host must acknowledge that it received each TCP segment. Remember, a segment is the Layer 4 PDU (like a packet at Layer 3 and frame at Layer 2). If the source host does not receive an acknowledgment for a segment, it is sent again.

### Sequencing

The sequence numbers in the TCP header allow destination hosts to put segments in the correct order even if they arrive out of order.

### Flow Control

The destination host can tell the source host to increase or decrease the rate that data is sent, so that it is not overwhelmed by receiving traffic faster than it can process.

## TCP Header

The TCP header has quite a few fields used to provide all those services. You do not need to memorize the entire header for the CCNA, but you should know these fields:

* **Source and Destination Port** -- each is 16 bits (2 bytes), meaning 65536 (2^16) total available port numbers
* **Sequence Number** and **Acknowledgment Number** -- used for sequencing and reliable communication
* **Flags** -- ACK (acknowledgment), SYN (synchronization), FIN (finish) -- used to establish and terminate connections
* **Window Size** -- used for flow control, adjusting the rate at which data is sent

```mermaid
flowchart LR
    subgraph TCPHeader["TCP Header (simplified)"]
        direction LR
        SP["Source Port<br/>(16 bits)"]
        DP["Destination Port<br/>(16 bits)"]
        SN["Sequence Number<br/>(32 bits)"]
        AN["Acknowledgment Number<br/>(32 bits)"]
        Flags["Flags<br/>ACK, SYN, FIN"]
        WS["Window Size<br/>(16 bits)"]
    end
```

## Establishing TCP Connections: 3-Way Handshake

TCP is connection-oriented, so hosts first communicate to establish a connection before sending data. The method is called the **TCP Three-Way Handshake** because it involves three messages.

PC1 wants to access a webpage on SRV1 using HTTP. First it must establish a TCP connection using the SYN and ACK flags.

```mermaid
sequenceDiagram
    participant PC1 as PC1
    participant SRV1 as SRV1

    Note over PC1,SRV1: 3-Way Handshake
    PC1->>SRV1: SYN (sequence number set)
    SRV1->>PC1: SYN-ACK (both SYN and ACK flags set)
    PC1->>SRV1: ACK (ACK flag set)
    Note over PC1,SRV1: Connection established, data exchange can begin
```

The three steps:

1. PC1 sends a TCP segment with the **SYN** flag set
2. SRV1 replies with **SYN and ACK** flags set
3. PC1 sends a segment with the **ACK** flag set

The first three messages are just to establish a connection. Remember: SYN, SYN-ACK, ACK.

## Terminating TCP Connections: 4-Way Handshake

When PC1 decides it no longer needs the connection with SRV1, it initiates termination using the FIN and ACK flags. This is sometimes called the "four-way handshake."

```mermaid
sequenceDiagram
    participant PC1 as PC1
    participant SRV1 as SRV1

    Note over PC1,SRV1: 4-Way Handshake (termination)
    PC1->>SRV1: FIN
    SRV1->>PC1: ACK
    SRV1->>PC1: FIN
    PC1->>SRV1: ACK
    Note over PC1,SRV1: Connection terminated
```

The four steps:

1. PC1 sends **FIN**
2. SRV1 responds with **ACK**
3. SRV1 sends its own **FIN**
4. PC1 responds with **ACK**

Before exchanging data, PC1 and SRV1 established a connection. After exchanging data, they terminate it. That is what "connection-oriented" means.

## TCP Sequencing and Acknowledgment

TCP uses sequence and acknowledgment fields to provide reliable communication and sequencing.

### Forward Acknowledgment

When PC1 sends the three-way handshake's SYN message, it sets a random initial sequence number -- let us say 10. When PC2 sends the SYN-ACK, it sets its own random initial sequence number, for example 50. It also acknowledges PC1's segment by setting the acknowledgment field to 11.

Why 11? TCP uses **forward acknowledgment**. Instead of acknowledging sequence number 10 with an ack of 10, it tells PC1 the sequence number of the next segment it expects to receive.

```mermaid
sequenceDiagram
    participant PC1 as PC1
    participant PC2 as PC2

    Note over PC1,PC2: 3-Way Handshake with sequencing
    PC1->>PC2: SYN, seq=10
    PC2->>PC1: SYN-ACK, seq=50, ack=11
    PC1->>PC2: ACK, seq=11, ack=51
    Note over PC1,PC2: Forward acknowledgment = next expected sequence
```

The exchange continues with each side tracking the other's sequence numbers and acknowledging the next expected segment.

### TCP Retransmission

If a segment is not acknowledged, it is sent again.

```mermaid
sequenceDiagram
    participant PC1 as PC1
    participant SRV1 as SRV1

    PC1->>SRV1: seq=20
    SRV1->>PC1: ack=21
    PC1->>SRV1: seq=21 (lost!)
    Note over PC1: No ACK received, timeout
    PC1->>SRV1: seq=21 (retransmit)
    SRV1->>PC1: ack=22
    Note over PC1,SRV1: Retransmission after timeout
```

PC1 sends segment 20, SRV1 acknowledges with ack 21. PC1 sends segment 21, but it does not reach SRV1. After waiting a certain amount of time with no ack, PC1 resends the segment. SRV1 receives it this time and sends ack 22.

## Flow Control

Acknowledging every single segment, no matter what size, is inefficient. The TCP header's **window size** field allows more data to be sent before an acknowledgment is required.

```mermaid
sequenceDiagram
    participant PC1 as PC1
    participant SRV1 as SRV1

    PC1->>SRV1: seq=20
    PC1->>SRV1: seq=21
    PC1->>SRV1: seq=22
    SRV1->>PC1: ack=23
    Note over PC1,SRV1: Multiple segments before ACK required
```

A **sliding window** is used to dynamically adjust the window size. The window size increases as much as possible until a segment is dropped, then it backs down to a more reasonable level and slowly increases again.

In real situations, sequence numbers get much larger and do not increase by 1 with each message, especially when the sliding window size gets very large. For the CCNA, just understand the concepts and do not worry about exact numbers.

## UDP

UDP (User Datagram Protocol) is much simpler than TCP. It can be summed up in one slide:

* **Connectionless** -- the sending host does not establish a connection before sending data. It is simply sent.
* **No reliable communication** -- acknowledgments are not sent. If a segment is lost, UDP has no mechanism to retransmit it. Segments are sent "best-effort" -- no guarantee of delivery.
* **No sequencing** -- UDP has no sequence field in its header. If segments arrive out of order, UDP has no mechanism to put them back in order.
* **No flow control** -- no mechanism like TCP's window size to control the rate of data.

### UDP Header

The UDP header has only four fields:

* Source port number
* Destination port number
* Length (length of the segment)
* Checksum (for error checking)

That is it. Compare this to TCP's many fields.

```mermaid
flowchart LR
    subgraph UDPHeader["UDP Header (4 fields only)"]
        direction LR
        SP["Source Port"]
        DP["Destination Port"]
        LEN["Length"]
        CS["Checksum"]
    end

    subgraph TCPHeader2["TCP Header (many fields)"]
        direction LR
        TSP["Source Port"]
        TDP["Destination Port"]
        TSN["Sequence Number"]
        TAN["Ack Number"]
        TFlags["Flags"]
        TWS["Window Size"]
        TCS["Checksum"]
        Turg["Urgent Pointer"]
        Topt["Options"]
    end
```

## TCP vs UDP Comparison

TCP provides more features than UDP, but at the cost of additional overhead because of the larger header. In addition, acknowledgments and retransmissions can slow down the transfer of data.

For applications that require reliable communications, TCP is preferred:

* Downloading a file -- you would not want to download a PDF with a page missing

For applications like real-time voice and video, UDP is preferred:

* Voice over IP phone calls, Zoom, Skype -- these are very delay-sensitive, you do not want the overhead of TCP slowing things down

If audio cuts out during a Skype call, you simply ask the other person to repeat what they said. In effect, you are asking for a "retransmission" -- but the application handles it, not the protocol.

Some applications use UDP but provide reliability within the application itself. TFTP (Trivial File Transfer Protocol) is one such example.

DNS (Domain Name System) uses both TCP and UDP depending on the situation.

```mermaid
flowchart TB
    subgraph TCP_Features["TCP"]
        direction TB
        T1["Connection-oriented"]
        T2["Reliable (ACKs + retransmit)"]
        T3["Sequencing"]
        T4["Flow control (window)"]
        T5["Larger header, more overhead"]
    end
    subgraph UDP_Features["UDP"]
        direction TB
        U1["Connectionless"]
        U2["Best-effort (no ACKs)"]
        U3["No sequencing"]
        U4["No flow control"]
        U5["Smaller header, less overhead"]
    end
```

## Important Port Numbers

Both TCP and UDP provide Layer 4 addressing in the form of port numbers. These port numbers identify Application Layer protocols and allow for session multiplexing. Memorize these well-known port numbers:

### TCP Port Numbers

| Port | Protocol      | Purpose                                      |
| ---- | ------------- | -------------------------------------------- |
| 20   | FTP (data)    | File Transfer Protocol data transfers        |
| 21   | FTP (control) | File Transfer Protocol control commands      |
| 22   | SSH           | Secure Shell, connecting to device CLIs      |
| 23   | Telnet        | Connecting to device CLIs (insecure)         |
| 25   | SMTP          | Simple Mail Transfer Protocol, sending email |
| 80   | HTTP          | Hypertext Transfer Protocol, web pages       |
| 110  | POP3          | Post Office Protocol 3, retrieving email     |
| 443  | HTTPS         | HTTP Secure, encrypted web pages             |

### UDP Port Numbers

| Port | Protocol      | Purpose                                  |
| ---- | ------------- | ---------------------------------------- |
| 67   | DHCP (server) | Dynamic Host Configuration Protocol      |
| 68   | DHCP (client) | Dynamic Host Configuration Protocol      |
| 69   | TFTP          | Trivial File Transfer Protocol           |
| 161  | SNMP          | Simple Network Management Protocol       |
| 162  | SNMP (trap)   | Simple Network Management Protocol traps |
| 514  | Syslog        | System logging protocol                  |

### Uses Both TCP and UDP

| Port | Protocol | Purpose                                         |
| ---- | -------- | ----------------------------------------------- |
| 53   | DNS      | Domain Name System (usually UDP, sometimes TCP) |

```mermaid
flowchart TB
    subgraph TCP_Protocols["Protocols using TCP"]
        direction TB
        FTP["FTP (20, 21)"]
        SSH2["SSH (22)"]
        Tel["Telnet (23)"]
        SMTP2["SMTP (25)"]
        HTTP2["HTTP (80)"]
        POP["POP3 (110)"]
        HTTPS2["HTTPS (443)"]
    end
    subgraph UDP_Protocols["Protocols using UDP"]
        direction TB
        DHCP2["DHCP (67, 68)"]
        TFTP2["TFTP (69)"]
        SNMP2["SNMP (161, 162)"]
        Syslog2["Syslog (514)"]
    end
    subgraph Both["Uses both TCP and UDP"]
        DNS2["DNS (53)"]
    end
```

***

## See also

* [TCP/IP Model](/my-docs/basic-networking/tcp_ip_model_ccna_day3.md) — the layered model that TCP and UDP operate within

***

## Resource

* [Free CCNA | TCP & UDP | Day 30 | CCNA 200-301 Complete Course -- Jeremy's IT Lab](https://www.youtube.com/watch?v=LIEACBqlntY)
