# TCP vs UDP

The Transport Layer in the OSI model and the TCP/IP model handles end-to-end communication. It connects applications that run on separate devices.&#x20;

Two key protocols work at this layer.&#x20;

* TCP stands for Transmission Control Protocol. It offers reliable service in a connection-oriented way. TCP also ensures the integrity of data that gets sent.&#x20;
* UDP means User Datagram Protocol. It stays lightweight and connectionless by design. UDP prioritizes speed over other features.&#x20;

Both TCP and UDP rely on ports to pinpoint specific applications and services. (e.g., HTTP uses port 80, DNS uses port 53).

<mark style="color:blue;">**Differences Between TCP and UDP**</mark>

| Feature            | TCP (Transmission Control Protocol)                    | UDP (User Datagram Protocol)         |
| ------------------ | ------------------------------------------------------ | ------------------------------------ |
| **Connection**     | Connection-oriented (requires a session before data)   | Connectionless (no setup required)   |
| **Reliability**    | Ensures delivery, retransmits lost packets             | No guarantee of delivery             |
| **Error Checking** | Error detection and correcti**on**                     | Error detection only                 |
| **Order**          | Ensures packets arrive in correct order                | Packets may arrive out of order      |
| **Flow Control**   | Yes (sliding window, congestion control)               | No                                   |
| **Speed**          | Slower due to overhead                                 | Faster, less overhead                |
| **Packet Size**    | Larger headers (20+ bytes)                             | Smaller headers (8 bytes)            |
| **Use Cases**      | Web browsing, email, file transfer, secure connections | Streaming, gaming, VoIP, DNS queries |

<mark style="color:blue;">**TCP**</mark>

TCP handles the reliable **delivery of data** between applications. It makes sure everything arrives in order and checks for errors along the way. That setup comes through something called the ***three-way handshake***.&#x20;

* The client starts things off by sending a SYN packet to the server. This is basically a request to synchronize and get ready for communication.&#x20;
* Then the server replies with a SYN-ACK packet. It acknowledges what the client sent and includes its own synchronization request right there.&#x20;
* Finally the client sends back an ACK packet to confirm the server's response. At that point the connection is fully established and ready to go. Data exchange only begins once all these steps wrap up.

```
Client                     Server
   | --- SYN -------------> |
   | <--- SYN-ACK -------- |
   | --- ACK -------------> |
Connection established
```

TCP has some key features that make it reliable for data transfer.&#x20;

One big thing is **reliability**. Lost packets get retransmitted so nothing important slips away. Then there is **segmentation** and **reassembly**. Large data gets split into **smaller segments**. Those segments reassemble at the destination end. **Flow control** helps too. It stops a fast sender from overwhelming a slow receiver. Congestion control adjusts the transmission rate. This happens when the network feels overloaded.&#x20;

People use TCP in various protocols. For example HTTP and HTTPS handle web browsing. SMTP IMAP and POP3 manage email stuff. FTP takes care of file transfers. SSH provides secure remote login access.

<mark style="color:blue;">**UDP**</mark>

UDP deals with speed and keeps things light on overhead. It works best for apps where you need real-time action more than perfect reliability.

One key thing about UDP is that there is **no handshake** at all. Data just gets sent right away without any back and forth. It also skips retransmission entirely. **Lost packets** get dropped and that is it. Packets can show up out of order too. They might arrive in whatever sequence they want. The header stays minimal at only eight bytes. That compares to twenty or more in something like TCP.

You see UDP in protocols like DNS for queries and responses. It handles DHCP for assigning addresses too. VoIP relies on it for voice over IP calls. Online gaming uses it a lot. Video and audio streaming depend on UDP as well.

<mark style="color:blue;">**Summary Table: TCP vs UDP Use Cases**</mark>

| Application         | Protocol | Reason                                         |
| ------------------- | -------- | ---------------------------------------------- |
| **Web Browsing**    | TCP      | Requires reliability and order                 |
| **Email**           | TCP      | Complete and error-free transfer is essential  |
| **File Transfer**   | TCP      | Integrity is critical                          |
| **Video Streaming** | UDP      | Real-time delivery, tolerates some packet loss |
| **Online Gaming**   | UDP      | Speed and low latency are critical             |
| **DNS Queries**     | UDP      | Simple, fast, small packets                    |

<mark style="color:blue;">**Structure of a UDP Datagram**</mark>

A **UDP datagram** is very simple and designed for minimal overhead. The header is fixed (8 bytes) and contains only what is necessary for basic multiplexing and error detection.

**UDP header fields:**

| Field       | Size (bits) | Description                                                |
| ----------- | ----------- | ---------------------------------------------------------- |
| Source Port | 16          | Port of sender (optional: 0 if unused)                     |
| Dest Port   | 16          | Destination application port                               |
| Length      | 16          | Length of header + data (in bytes)                         |
| Checksum    | 16          | Optional in IPv4, mandatory in IPv6 — covers header + data |

**Layout (bits)**

```
0                   15                  31
+-------------------+-------------------+
| Source Port (16)  | Dest Port (16)    |
+-------------------+-------------------+
| Length (16)       | Checksum (16)     |
+-------------------+-------------------+
| Data ...                              |
```

Notes:

* The **Length** field includes the 8-byte UDP header plus payload.
* The **Checksum** protects against corruption between endpoints; on IPv4 it may be zero (disabled) but on IPv6 it is required.
* Because the header is minimal, UDP has low processing overhead and is suitable for real-time applications.

<mark style="color:blue;">**Structure of a TCP Segment**</mark>

A **TCP segment** is more complex because TCP provides reliability, ordering, flow control and congestion control. The TCP header has a minimum size of 20 bytes and can grow when options are present.

**Main TCP header fields:**

| Field             | Size (bits) | Description                                                                |
| ----------------- | ----------- | -------------------------------------------------------------------------- |
| Source Port       | 16          | Sender application port                                                    |
| Destination Port  | 16          | Receiver application port                                                  |
| Sequence Number   | 32          | Byte offset of first data octet in this segment                            |
| Acknowledgment #  | 32          | Next sequence number the sender of this segment expects (valid if ACK set) |
| Data Offset       | 4           | Header length in 32-bit words (min = 5 => 20 bytes)                        |
| Reserved          | 3           | Reserved for future use (must be zero)                                     |
| Flags             | 9           | Control bits (NS, CWR, ECE, URG, ACK, PSH, RST, SYN, FIN)                  |
| Window Size       | 16          | Flow-control window (how many bytes can be accepted)                       |
| Checksum          | 16          | Checksum of header + data + pseudo-header                                  |
| Urgent Pointer    | 16          | Points to urgent data if URG flag is set                                   |
| Options + Padding | variable    | Optional features (MSS, Window Scale, SACK, Timestamps)                    |

**Layout (bits)**

```
  0                   15                  31
  +-------------------+-------------------+
  |   Source Port (16) | Destination Port (16) |
  +-------------------+-------------------+
  |                Sequence Number (32)                |
  +----------------------------------------------------+
  |             Acknowledgment Number (32)             |
  +--------+--------+--------+-------------------------+
  | Data   |  Res.  | Flags  |       Window (16)       |
  | Offset | (3 bits)| (9 bits)                        |
  +-----------------+----------------------------------+
  |     Checksum (16)       |  Urgent Pointer (16)     |
  +----------------------------------------------------+
  |                 Options (variable)                 |
  +----------------------------------------------------+
  |                     Data ...                       |
  +----------------------------------------------------+
```

We are still talking about the fundamental parts of TCP headers. They are what enable the protocol to function correctly. Let's analyze some important fields.

TCP sees the data stream as a long sequence of bytes. Each individual byte is assigned its own sequence number. The **Sequence Number** field indicates the starting point of the first data byte in that segment. This setting is very useful for maintaining order and managing any retransmissions.

When the ACK flag turns on, the **Acknowledgment Number** field holds the next sequence number that the ACK sender is waiting for. It basically confirms that all the bytes before that one are good to go.

* ***Flags act as control bits in the header, and are:***
  * **SYN**: Synchronize — used to open a connection (consumes one sequence number).
  * **ACK**: Acknowledgment field is valid.
  * **FIN**: Graceful connection close (consumes one sequence number).
  * **RST**: Reset connection immediately.
  * **PSH**: Push — prompt receiver to pass data to application.
  * **URG**: Urgent pointer is valid.
  * **ECE, CWR, NS**: Extensions for congestion control and ECN.
* The **Window Size** field comes from the receiver. It tells the sender exactly how many bytes it can handle at once for flow control. The sender has to stick to that limit and not flood it with more unacknowledged data than allowed.
* **Options** in the header let both sides negotiate extra features. Some common:
  * **MSS** **(Maximum Segment Size)**, which sets the maximum segment size for payload that the sender can deal with.
  * **Window Scale** bumps up the window beyond 65,535 bytes when needed.
  * **SACK (Selective Acknowledgement)** allows selective acknowledgments for non-contiguous data blocks, which really helps recovery.
  * **Timestamps** measure round-trip time and deal with PAWS issues.

Headers add some overhead to the packets. The basic TCP header runs 20 bytes without any options. With options added in, it usually hits 20 to 60 bytes. UDP keeps it simple at just 8 bytes for its header.

<mark style="color:blue;">**Comparison: Header Size & Overhead**</mark>

| Protocol | Header Size (min) | Typical Overhead | Use Case Notes                |
| -------- | ----------------: | ---------------: | ----------------------------- |
| UDP      |           8 bytes |              Low | Real-time, stateless traffic  |
| TCP      |          20 bytes |  Higher (20–60B) | Reliable streams, connections |
