TCP & UDP Protocols

Jay KadlagJay Kadlag
18 min read

Introduction

Every second, messages, videos, and files move across the internet, connecting people and devices everywhere. But how does all this data travel so smoothly? The answer lies in two important ways of communication—TCP (Transmission Control Protocol) and UDP (User Datagram Protocol).

Think of the internet like a busy road. Some vehicles follow strict traffic rules, making sure every passenger reaches safely—this is TCP. Others move fast, weaving through traffic without stopping too much—this is UDP.

These two methods decide how data moves from one place to another. TCP makes sure nothing gets lost, while UDP focuses on speed, getting data delivered as quickly as possible. Both are important but used for different things.

In this article, we’ll explore how TCP and UDP work, where they are used, how they function, their benefits, drawbacks, and real-life applications. We’ll also see why they are important for things like web browsing, video calls, and online gaming.

UDP (User Datagram Protocol)

What Is UDP?

UDP is a basic and widely used protocol for network communication. It works at Layer 4 (Transport Layer) of the OSI model, directly on top of the Internet Protocol (IP) layer.

Unlike other protocols, UDP doesn’t establish a connection before sending data, making it faster but also less reliable—some data packets might get lost along the way. It is also known as the "fire-and-forget" protocol as it sends the data and does not care whether the data is received or not.

Why It Is Used?

UDP is great for situations where speed matters more than perfection. It’s used for things like online calls (VoIP) and video streaming because a little bit of missing data (like a quick glitch or static) is better than long delays. That’s why most internet-based phone calls use UDP—it’s better to have a slightly choppy conversation than one with annoying pauses.

The same goes for online gaming, where fast response times are crucial. If a few data packets get lost, it’s still better than lagging behind in the game. Even DNS (which helps your browser find websites) uses UDP because it needs to work quickly and efficiently.

Besides gaming and streaming, UDP is widely used in IoT (Internet of Things) devices, where sensors need to send data quickly and don’t require confirmation. It’s also used in real-time applications like stock market price updates, where speed is more critical than occasional missing data.

Main features of UDP

  • Stateless Protocol: UDP is stateless, meaning that it doesn't maintain a connection between the sender and receiver. Each datagram (packet) is sent independently, without knowing if the destination is ready or even exists.

  • No Prior Communication Required: Since it’s stateless, UDP can send data immediately, making it faster than connection-based protocols like TCP.

  • Simple and Minimal Header: UDP's header is only 8 bytes long, much smaller than TCP's header, which means less extra data is added, making it efficient and quick.

  • Broadcast and Multicast Support: UDP allows data to be sent to multiple devices at once, making it ideal for applications like live streaming, online multiplayer games, and network discovery services (e.g., DHCP).

UDP Packet Format

A UDP packet, also called a datagram, has two main parts: a header and a data section. Its simple structure makes UDP fast and efficient.

  • Header – This is the control information of the message and is 8 bytes in size.

  • Data – This is the actual content being sent and can be any size, up to 65,535 bytes. It carries the main information, such as a DNS request or a video stream packet.

UDP Header Structure

The UDP header is very small, only 8 bytes long, which makes it fast and efficient.

UDP Header Fields:

  1. Source Port (16 bits) – Identifies the port of the sending application. This is used by the receiver to know where to send a response.

  2. Destination Port (16 bits) – Identifies the port of the receiving application. This tells the receiver’s system which application should process the incoming datagram.

  3. Length (16 bits) – Specifies the total length of the UDP datagram, including both the header and the data. This helps in determining the boundaries of the datagram.

  4. Checksum (16 bits): Used for error-checking of the header and data. This ensures the integrity of the data during transmission. It is optional in IPv4 but mandatory in IPv6.

The checksum makes sure that the data is not altered(changed) during transmission. It is calculated using the pseudo header, UDP header, and UDP payload.

UDP Ports

UDP Ports help applications and services communicate without needing a connection. Since UDP is connectionless, these port numbers allow data to be sent without a persistent link between sender and receiver.

UDP ports range from 0 to 65,535 and are divided into three types:

  1. Well-Known Ports (0-1023) – Used for standard services like:

    • DNS (Port 53) – Resolves domain names.

    • DHCP (Ports 67/68) – Assigns IP addresses.

    • NTP (Port 123) – Synchronizes time.

  2. Registered Ports (1024-49151) – Assigned to specific applications.

  3. Dynamic/Private Ports (49152-65535) – Used temporarily for short-lived connections, often within a system.

Unlike TCP ports, which require a connection, UDP ports remain stateless, meaning there is no session tracking. This makes UDP faster but less reliable, as it does not confirm if data is received.

Common Uses of UDP Ports:

  • Streaming (YouTube, Netflix)

  • VoIP (Skype, Zoom)

  • Online Gaming

  • DNS Queries

  • Time Synchronization

Working of UDP

  1. Packaging the Data -

    • The process starts when an application decides to send data using UDP. This data could be anything from a DNS request to a video streaming packet.

    • The application packages the data into a UDP datagram to prepare it for transmission.

  2. Adding Headers & Creating the Datagram -

    • The UDP layer then adds a small header to this datagram.

    • This header contains:

      • Source Port and Destination Port – These ensure the data reaches the correct application.

      • Length of the Datagram – Specifies the size of the data.

      • Checksum – Helps detect errors during transmission.

    • The UDP header is added to the application data, forming a complete UDP datagram. This datagram is then packed into an IP packet for delivery.

  3. Passing Through the IP Layer & Network Layer

    • The UDP datagram moves to the Internet Protocol (IP) layer, where another header is added.

    • This IP header contains:

      • Sender’s IP Address – Identifies where the data is coming from.

      • Receiver’s IP Address – Specifies where the data needs to go.

    • The IP packet is then wrapped inside a network frame (like Ethernet) so it can be sent over the physical network.

  4. Sending the Data Over the Network

    • The network frame is sent across the internet, passing through routers and network segments until it reaches the final destination.
  5. Receiving & Processing the Data

    Once the data arrives at the destination:

    • The network frame is removed, revealing the IP packet.

    • The IP layer processes the packet and extracts the UDP datagram.

    • The UDP layer verifies the checksum (if used) and checks the destination port to see which application needs the data.

  6. Delivering Data to the Application

    • Finally, the receiving application extracts the original data from the UDP datagram and processes it.

    • This could mean:

      • A video streaming app plays the video smoothly.

      • A game updates player actions in real-time.

      • A browser resolves a website address using DNS.

Advantages of UDP

  1. No Connection Needed – UDP does not require a connection between sender and receiver, making it faster and more efficient.

  2. Supports Broadcast and Multicast – It allows data to be sent to multiple devices at once, which is useful for streaming and gaming.

  3. Works on Various Networks – UDP can function across different types of networks, making it highly adaptable.

  4. Ideal for Real-Time Data – It is commonly used for live video, online gaming, and VoIP because of its low latency.

  5. Delivers Data Even If Some Parts Are Missing – Unlike TCP, UDP does not wait for all parts of the data before delivering it, making it faster in real-time scenarios.

Disadvantages of UDP

  1. No Acknowledgment of Delivery – There is no way to confirm whether the data was successfully received.

  2. No Order Guarantee – UDP does not track the sequence of packets, so data may arrive out of order.

  3. Unreliable Due to Being Connectionless – Since UDP does not establish a connection before sending data, some packets may get lost without any recovery mechanism.

  4. Packets Can Be Dropped in Collisions – In case of network congestion or packet collision, routers tend to drop UDP packets more often than TCP packets.

  5. No Built-in Error Handling – If an error is detected in a packet, UDP does not attempt to fix or resend it, which can lead to data loss.

Applications of UDP

  1. Streaming Audio & Video – UDP is widely used in platforms like YouTube Live, Netflix, and Spotify because it ensures smooth playback with minimal delay, even if some data is lost.

  2. Online Gaming – Multiplayer games like PUBG, Call of Duty, and Fortnite use UDP for fast communication between players, reducing lag.

  3. DNS (Domain Name System) Queries – When you type a website name, UDP helps quickly convert it into an IP address, allowing faster web browsing.

  4. Network Monitoring – Tools that track network performance use UDP for fast, lightweight data exchange without delays.

  5. Multicasting – UDP enables sending data to multiple users at once, making it useful for IPTV, live broadcasts, and real-time notifications.

  6. Routing Protocols – Some network routing protocols, like RIP (Routing Information Protocol), rely on UDP to exchange routing updates efficiently.

How is UDP used in DDoS attacks?

UDP has some risks, but they’re usually not a big deal in most cases. However, because UDP doesn’t need a handshake before sending data, attackers can misuse it to overwhelm a server with fake traffic. This is called a UDP flood attack.

In this, the attacker sends tons of UDP packets to random ports on a target computer. The target tries to respond with ICMP messages saying those ports are unreachable. Since this requires processing power, the server can get overloaded and stop working properly, blocking real users from accessing it.

To prevent this, organizations use different strategies. One way is to limit how many ICMP responses a server sends, though this can sometimes block legitimate traffic too. Another way is to route UDP traffic through a distributed network of multiple data centers, so no single server gets overwhelmed.

Another common UDP-based attack is the UDP amplification attack, where an attacker sends small requests to open UDP services like DNS or NTP with a spoofed source IP (the victim’s IP). These services respond with much larger data packets, overwhelming the victim’s bandwidth.

TCP (Transmission Control Protocol)

What Is TCP?

TCP (Transmission Control Protocol) is one of the most commonly used network protocols. It operates at Layer 4 (Transport Layer) of the OSI model, sitting directly on top of the Internet Protocol (IP) layer.

Unlike UDP, TCP establishes a connection before sending data, ensuring that every packet reaches its destination correctly and in the right order. This makes TCP highly reliable but also a bit slower compared to UDP.

Why It Is Used?

TCP is used in situations where accuracy and reliability matter more than speed. It’s the backbone of internet communication when you need guaranteed data delivery.

For example, web browsing (HTTP/HTTPS) relies on TCP because when you load a webpage, you want every part of the page—text, images, and videos—to arrive intact and in order. Imagine reading an article where random paragraphs go missing—that’s what TCP prevents!

The same goes for file transfers (FTP, SFTP) and email (SMTP, IMAP, POP3). If you’re downloading a file, you can’t afford to have missing chunks—it would corrupt the file. TCP makes sure every part is received properly, even if it has to retransmit some packets.

Another important use case is online banking and transactions. When you transfer money or send sensitive data, you don’t want even a single bit to be lost or arrive out of order. TCP ensures secure, complete, and error-free transmission.

Even video streaming platforms like Netflix and YouTube use TCP in certain cases, especially when buffering is preferred over missing video frames. This ensures that a high-quality stream is delivered without errors.

Main Features of TCP

  • Reliable Transmission: TCP makes sure that all data is delivered correctly and in the right order.

  • Error Detection and Correction: It checks for errors using checksums and resends data if something goes wrong.

  • Three-Way Handshake: Before sending data, TCP sets up a connection using a three-step process (SYN, SYN-ACK, and ACK) to ensure both devices are ready to communicate.

  • Stateful Protocol: TCP keeps track of the connection, making communication stable and reliable.

  • Multiplexing: It allows multiple applications on the same device to communicate at the same time using different ports.

  • Addressing: TCP uses both IP addresses and port numbers to create unique paths for data to travel.

TCP Packet Format

A TCP segment is placed inside an IP packet before being sent over the network.

  • Header – The header size starts at 20 bytes but can grow up to 60 bytes if extra options are added.

  • Data – The data section contains the actual information being sent, such as a webpage, file, or message, and can vary in size depending on the network conditions and TCP settings.

TCP Header Structure

The TCP header starts at 20 bytes, providing reliability and control but adding more overhead than UDP.

TCP Header Fields:

  1. Source Port (16 bits): Identifies the port number of the sender’s application.

  2. Destination Port (16 bits): Identifies the port number of the receiving application.

  3. Sequence Number (32 bits): Ensures that data packets are reassembled in the correct order upon arrival.

  4. Acknowledgment Number (32 bits): Indicates the next expected byte from the sender, confirming successful receipt of previous data.

  5. Data Offset (4 bits): Specifies the length of the TCP header in multiples of 32-bit words.

  6. Reserved (3 bits): Reserved for future use and always set to zero.

  7. Flags (9 bits): Control flags that help manage TCP communication, including:

    • URG: Indicates that the urgent pointer field contains important data.

    • ACK: Confirms receipt of data and acknowledges the next expected byte.

    • PSH: Requests immediate delivery of data to the receiving application.

    • RST: Resets the connection if an error occurs or the communication is disrupted.

    • SYN: Initiates a new connection and synchronizes sequence numbers.

    • FIN: Indicates that the sender has no more data to transmit.

    • ECE (Explicit Congestion Notification Echo): Alerts the sender that network congestion is occurring, allowing it to reduce transmission speed.

    • CWR (Congestion Window Reduced): Informs the receiver that the sender has adjusted its data flow in response to congestion.

    • NS (Nonce Sum): An experimental flag that helps prevent data tampering during transmission.

  8. Window Size (16 bits): Specifies the amount of data (in bytes) the receiver is ready to accept at one time. The default maximum is 65,535 bytes, but this can be increased using the window scaling option.

  9. Checksum (16 bits): Used to verify data integrity and detect transmission errors in the header and data.

  10. Urgent Pointer (16 bits): Points to urgent data if the URG flag is set, ensuring it is processed immediately.

  11. Options (variable length): Allows additional settings to enhance TCP functionality and performance. The header is padded to maintain proper alignment.

  12. Padding (variable length): Extra bits added to ensure the header length is a multiple of 32 bits for proper data alignment.

TCP Ports

TCP ports help applications and services communicate by establishing reliable connections. Since TCP is connection-oriented, these port numbers ensure that data is sent and received in an organized and error-free manner.

TCP ports range from 0 to 65,535 and are categorized into three types:

  1. Well-Known Ports (0-1023): Reserved for standard services like:

    • HTTP (Port 80): Handles web traffic.

    • HTTPS (Port 443): Secure web browsing.

    • FTP (Port 21): File transfers.

    • SSH (Port 22): Secure remote access.

  2. Registered Ports (1024-49151): Assigned to specific applications and services.

  3. Dynamic/Private Ports (49152-65535): Used temporarily for short-lived connections, such as browsing sessions or streaming.

Unlike UDP ports, which are stateless, TCP ports maintain a connection for session tracking and error handling, making TCP more reliable but slightly slower.

Common Uses of TCP Ports:

  • Web Browsing (HTTP - Port 80, HTTPS - Port 443)

  • File Transfers (FTP - Port 21, SFTP - Port 22)

  • Email Services (SMTP - Port 25, IMAP - Port 143, POP3 - Port 110)

  • Remote Access (SSH - Port 22, Telnet - Port 23, RDP - Port 3389)

  • Database Communication (MySQL - Port 3306, PostgreSQL - Port 5432, SQL Server - Port 1433)

  • Online Transactions & Banking

  • Cloud Services & API Communications

  • Secure Communication (TLS/SSL - Port 443)

TCP Working

  1. Packaging the Data

    • The process begins when an application decides to send data using TCP. This data could be anything from a web page request to an email or a file transfer.

    • TCP breaks the data into segments and prepares it for transmission.

  2. Adding Headers & Creating the TCP Segment

    • The TCP layer adds a header to each segment, which contains:

      • Source Port and Destination Port – Ensure the data reaches the correct application.

      • Sequence Number – Keeps track of the order of data packets.

      • Acknowledgment Number – Confirms received data.

      • Flags (SYN, ACK, FIN, etc.) – Controls the communication process.

      • Checksum – Helps detect transmission errors.

    • This TCP segment is then packed into an IP packet for delivery.

  3. Establishing a Connection (Three-Way Handshake)

    Before sending data, TCP establishes a connection using a three-step handshake:

    1. SYN – The client sends a SYN packet to the server to initiate a connection.

    2. SYN-ACK – The server sends a SYN-ACK packet to confirm it received the SYN packet and to set up its own sequence number for communication.

    3. ACK – The client sends an ACK packet, completing the handshake and establishing a connection.

  4. Passing Through the IP & Network Layers

    • The TCP segment moves to the IP layer, where another header is added.

    • The IP header contains:

      1. Sender’s IP Address – Identifies the source.

      2. Receiver’s IP Address – Identifies the destination.

    • The IP packet is then wrapped inside a network frame (like Ethernet) and sent over the physical network.

  5. Sending Data Over the Network

    • The network frame travels across the internet, passing through routers and network segments, until it reaches the destination.
  6. Receiving & Processing the Data

    Once the data arrives at the destination:

    • The network frame is removed, revealing the IP packet.

    • The IP layer processes the packet and extracts the TCP segment.

    • The TCP layer verifies the checksum, reorders segments, and removes duplicates if necessary.

    • The acknowledgment number confirms successful receipt.

  7. Delivering Data to the Application

    • Finally, the receiving application extracts the original data and processes it.

    • This could mean:

      • A web browser loads a page.

      • An email application displays a message.

      • A file transfer completes successfully.

  1. Closing the Connection (Four-Way Handshake)

  • Once data transmission is complete, TCP gracefully closes the connection using a four-step process:

    1. FIN – The sender requests to end the session.

    2. ACK – The receiver acknowledges the request.

    3. FIN – The receiver also requests closure.

    4. ACK – The sender confirms, and the connection is closed.

Advantages of TCP

  • Reliable Transmission – TCP ensures data is delivered completely and in the correct order.

  • Error Detection & Correction – Uses checksums and retransmission to fix lost or corrupted data.

  • Connection-Oriented – Establishes a connection before data transfer, ensuring communication is stable.

  • Flow & Congestion Control – Adjusts data flow to prevent overwhelming the receiver or network.

  • Data Sequencing – Assigns sequence numbers to packets so they arrive in the correct order.

  • Supports Acknowledgment – Confirms the receipt of data, reducing the chances of data loss.

Disadvantages of TCP

  • Slower Than UDP – The extra reliability features make TCP slower.

  • Higher Overhead – Larger headers and acknowledgments increase data size and processing time.

  • Connection Setup Required – The three-way handshake adds a delay before data can be sent.

  • Not Ideal for Real-Time Applications – Retransmissions can cause delays in gaming and live streaming.

  • Consumes More Resources – TCP uses more system memory and processing power due to session tracking.

Applications of TCP

  • Web Browsing (HTTP/HTTPS) – Ensures web pages load completely and correctly.

  • File Transfers (FTP, SFTP) – Guarantees files are transferred without errors.

  • Email Services (SMTP, IMAP, POP3) – Ensures emails are sent and received properly.

  • Remote Access (SSH, Telnet, RDP) – Provides secure and stable connections to remote devices.

  • Online Transactions & Banking – Ensures secure and error-free money transfers.

  • Database Communication – Used by SQL-based databases for accurate data retrieval.

  • Cloud Services & APIs – Helps in reliable data exchange between applications.

How TCP Handles Congestion?

TCP includes built-in congestion control to prevent network overload and ensure smooth data transmission. It uses the following methods:

  • Slow Start: TCP begins by sending small amounts of data and gradually increases the speed until it finds the network’s capacity.

  • Congestion Avoidance: If congestion is detected, TCP slows down data transmission to prevent further delays or packet loss.

  • Fast Retransmit & Recovery: If a packet is lost, TCP quickly resends it instead of waiting for a timeout.

  • Selective Acknowledgment (SACK): Instead of acknowledging each packet individually, TCP confirms multiple received packets at once, reducing unnecessary retransmissions.

How TCP Prevents Cyber Attacks?

Although TCP is a reliable protocol, it is still vulnerable to certain cyber attacks.

Some common threats include:

  • SYN Flood Attacks: Attackers send a large number of SYN requests but never complete the handshake, causing the server to become overloaded.

  • Session Hijacking: Hackers intercept active TCP connections to steal or modify sensitive data.

  • TCP Reset Attacks: Attackers send fake RST (reset) packets to forcefully close connections.

To protect against these attacks, mitigation strategies include:

  • Firewalls & Intrusion Prevention Systems (IPS): Monitor and block suspicious traffic.

  • SYN Cookies: Prevent SYN flood attacks by delaying resource allocation until the handshake is complete.

  • Encryption & Secure Protocols (TLS/SSL): Protect data from interception and tampering.

  • Rate Limiting: Restrict excessive requests from a single source to prevent server overload.

Conclusion

TCP and UDP help data move across the internet in different ways. TCP is reliable and ensures that all data arrives correctly, making it great for web browsing, emails, and file downloads. UDP focuses on speed, which is useful for online games, video calls, and streaming, even if some data is lost.

Choosing the right one depends on the need—TCP for accuracy and UDP for fast delivery. Both work together to keep the internet running smoothly.

Want More…?

I write articles on blog.devwithjay.com and also post development-related content on the following platforms:

210
Subscribe to my newsletter

Read articles from Jay Kadlag directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Jay Kadlag
Jay Kadlag