Back to all posts
Guide
12 min read

TCP vs UDP Explained: Key Differences, Use Cases & When to Use Each (2026)

DevToolLab Team

DevToolLab Team

May 22, 2026

TCP vs UDP Explained: Key Differences, Use Cases & When to Use Each (2026)

If you've ever set up a server, debugged a firewall rule, or tried to share a local game with friends, you've run into TCP and UDP. They're the two workhorses of internet communication - but they work in fundamentally different ways. This guide explains exactly what each protocol does, when to use which one, what ICMP ping actually is (spoiler: no ports involved), and how to set up port forwarding correctly.

TCP vs UDP

TCP (Transmission Control Protocol) guarantees your data arrives in order, complete, and without errors. It does this by establishing a connection before sending anything and retransmitting any lost packets.

UDP (User Datagram Protocol) is a fire-and-forget protocol. It sends packets as fast as possible without confirming they arrived. What it lacks in reliability it makes up for in raw speed.

FeatureTCPUDP
Connection3-way handshake requiredNone - connectionless
Delivery guaranteeYes - retransmits lost packetsNo guarantee
OrderingData arrives in orderPackets may arrive out of order
Error correctionFullChecksum only
SpeedSlower (more overhead)Faster (minimal overhead)
Header size20–60 bytes8 bytes (fixed)
Flow controlYes - sliding windowNone
Congestion controlYes - backs off under loadNone
Broadcast/MulticastNoYes
Best forWeb, databases, email, file transferStreaming, gaming, DNS, VoIP

How TCP Works: The 3-Way Handshake

Before TCP sends a single byte of data, it establishes a connection using a 3-way handshake:

  1. SYN - Client sends a synchronize packet: "I want to connect"
  2. SYN-ACK - Server replies: "OK, I'm ready"
  3. ACK - Client confirms: "Great, let's go"

Only after this handshake completes does actual data flow. Every packet TCP sends gets an acknowledgement (ACK) from the receiver. If an ACK doesn't arrive within a timeout, TCP retransmits the packet automatically.

This is why TCP is reliable but slower - every packet has overhead, and lost packets create delays while waiting for retransmission.

TCP Connection Termination (4-Way)

Closing a TCP connection is a 4-step process:

  1. Client sends FIN (finished)
  2. Server sends ACK
  3. Server sends its own FIN
  4. Client sends ACK

This graceful shutdown ensures both sides finish sending all data before the connection closes.

How UDP Works: Fire and Forget

UDP skips the handshake entirely. It just wraps your data in a small 8-byte header and sends it. There's no connection state, no acknowledgements, no retransmission.

Bash
UDP Header (8 bytes):
┌────────────────┬────────────────┐
│  Source Port   │ Dest Port      │  4 bytes
├────────────────┴────────────────┤
│  Length        │ Checksum       │  4 bytes
└─────────────────────────────────┘
│  Data (payload)...              │

The 8-byte UDP header versus TCP's 20–60 bytes is a significant advantage for applications that send thousands of small packets per second - like games, VoIP calls, or DNS queries.

Why Would You Want an Unreliable Protocol?

Because "unreliable" doesn't mean "broken" - it means "the application handles reliability itself, or doesn't need it."

  • Video streaming: A dropped frame is better than pausing to retransmit it. Your eyes wouldn't notice a single missed frame, but they would notice a half-second freeze.
  • Online gaming: A stale position update from 200ms ago is useless. Better to drop it and use the next fresh one.
  • DNS lookups: A query is a single small packet. If it drops, just send another - faster than maintaining a full TCP connection for a one-packet exchange.
  • VoIP calls: Like video - a dropped 20ms audio slice sounds like a slight crackle, which is better than the call pausing to retransmit.

Which Protocol Should You Use?

Use TCP when:

  • Data integrity is critical - HTTP/HTTPS, database queries, file transfers, email
  • You need to know the data arrived - API calls, form submissions, authentication
  • Packets must arrive in order - reading a file, loading a web page
  • You're building a standard web service - TCP is the default choice for servers

Use UDP when:

  • Speed matters more than perfection - live video, audio calls, gaming
  • You can tolerate some packet loss - a dropped frame or game position update
  • You're sending small, frequent messages - DNS, DHCP, IoT sensors, metrics
  • You need broadcast/multicast - service discovery, mDNS, SSDP
  • You're building a custom reliable transport - QUIC (used by HTTP/3) builds reliability on top of UDP to avoid TCP's head-of-line blocking

ICMP: The Ping Protocol (No Port Numbers)

This is one of the most common misconceptions in networking: ping does not use a port number.

Ping uses ICMP - Internet Control Message Protocol - which is a separate Layer 3 protocol, alongside TCP and UDP but not the same as them. ICMP has no concept of ports because it's not a transport protocol; it's a diagnostic/control protocol.

How ping works

ping google.com
  1. Your machine sends an ICMP Echo Request packet to the destination
  2. The destination replies with an ICMP Echo Reply
  3. Your machine measures the round-trip time

The output looks like this:

Bash
PING google.com: 56 data bytes
64 bytes from 142.250.80.46: icmp_seq=0 ttl=117 time=11.234 ms
64 bytes from 142.250.80.46: icmp_seq=1 ttl=117 time=10.891 ms
  • icmp_seq: packet sequence number
  • ttl: Time To Live - decremented at each router hop
  • time: round-trip latency in milliseconds

Why "ping port 80" is technically wrong

When developers say "ping port 80," they actually mean test a TCP connection to port 80. ICMP doesn't have ports. The tools that actually test a specific port are:

Bash
# Test if TCP port 443 is reachable
nc -zv google.com 443

# Same with telnet
telnet google.com 80

# Or with curl
curl -I https://google.com

traceroute / tracert

traceroute (Linux/Mac) and tracert (Windows) also use ICMP. They work by sending packets with incrementally increasing TTL values. Each router along the path decrements TTL and when it hits 0, sends back an ICMP Time Exceeded message - revealing its IP address and the latency to that hop.

Bash
traceroute google.com        # Linux / macOS
tracert google.com           # Windows

When ping fails but the server is running

Firewalls commonly block ICMP traffic. If ping fails, don't assume the server is down - use a TCP-based check instead:

Bash
# This works even if ICMP is blocked
curl -I --max-time 5 https://yourserver.com

Well-Known Ports Reference

Ports are divided into three ranges:

  • Well-Known Ports (0–1023): Assigned by IANA, used by system services. Require root/admin privileges to bind.
  • Registered Ports (1024–49151): Assigned to specific applications. No root required.
  • Dynamic/Ephemeral Ports (49152–65535): Used temporarily by client connections.

System / Web Ports

PortProtocolServiceDescription
20TCPFTP DataFTP active mode data transfer
21TCPFTP ControlFTP command and control
22TCPSSHEncrypted remote access and tunneling
23TCPTelnetUnencrypted terminal (obsolete - use SSH)
25TCPSMTPEmail delivery between servers
53TCP/UDPDNSDomain name lookups
67/68UDPDHCPDynamic IP address assignment
69UDPTFTPTrivial file transfer, used in PXE boot
80TCPHTTPUnencrypted web traffic
110TCPPOP3Email retrieval (legacy)
123UDPNTPNetwork time synchronization
143TCPIMAPEmail inbox access and sync
161/162UDPSNMPNetwork device monitoring
179TCPBGPInternet routing protocol
389TCP/UDPLDAPDirectory services and authentication
443TCPHTTPSEncrypted web traffic (TLS)
445TCPSMBWindows file sharing
465/587TCPSMTPS/SubmissionSecure email sending
636TCPLDAPSSecure LDAP over TLS
993TCPIMAPSSecure IMAP over TLS
995TCPPOP3SSecure POP3 over TLS

Database & Cache Ports

PortProtocolServiceDescription
1433TCPMSSQLMicrosoft SQL Server
1521TCPOracle DBOracle Database listener
3306TCPMySQL / MariaDBMost popular open-source relational DB
5432TCPPostgreSQLAdvanced open-source relational DB
5984TCPCouchDBDocument database with REST API
6379TCPRedisIn-memory cache and message broker
9200TCPElasticsearchSearch and analytics engine HTTP API
11211TCP/UDPMemcachedDistributed memory caching
27017TCPMongoDBNoSQL document database

DevOps & Messaging Ports

PortProtocolServiceDescription
2375TCPDocker (no TLS)Docker daemon REST API (unencrypted)
2376TCPDocker (TLS)Docker daemon REST API (encrypted)
3389TCP/UDPRDPWindows Remote Desktop
4369TCPErlang EPMUsed by RabbitMQ node discovery
5672TCPAMQP (RabbitMQ)Message queue protocol
5671TCPAMQPSSecure AMQP over TLS
6443TCPKubernetes APIkube-apiserver
8080TCPHTTP AltDev servers, proxies, Tomcat
9090TCPPrometheusMetrics and alerting
9092TCPApache KafkaMessage broker
15672TCPRabbitMQ UIWeb management console

Development Server Ports

PortProtocolServiceDescription
3000TCPReact / Next.js / Node.jsMost popular dev server port
3001TCPReact fallback / RemixWhen 3000 is occupied
4200TCPAngular CLIAngular dev server
4321TCPAstroAstro dev server
5173TCPViteVite-based dev servers
8000TCPDjango / FastAPIPython web frameworks
8888TCPJupyter NotebookData science notebooks
11434TCPOllamaLocal AI/LLM server

Port Forwarding

Port forwarding lets you expose a server running inside your home or office network to the public internet. Without it, your router's NAT firewall blocks all incoming connections.

How NAT (Network Address Translation) Works

Your router has one public IP address (e.g., 203.0.113.45) but assigns private IP addresses to all your devices (e.g., 192.168.1.x). When you connect outward, the router tracks the connection and routes replies back. But for incoming connections, the router has no way to know which device to forward them to - unless you tell it with a port forwarding rule.

Internet → Router (203.0.113.45:80) → Your Server (192.168.1.100:3000)

Step 1: Find Your Server's LAN IP

Linux / macOS:

Bash
ip addr show         # Linux
ifconfig             # macOS
# Look for inet 192.168.x.x under your active interface (eth0, en0, wlan0)

Windows:

cmd
ipconfig
# Look for IPv4 Address under your active adapter

Set your server's IP to a static LAN IP so it doesn't change after a reboot. Do this in your router's DHCP reservation settings using the device's MAC address.

Step 2: Access Your Router Admin Panel

Open a browser and navigate to your default gateway:

Bash
# Find your gateway
ip route | grep default      # Linux/Mac
# Output: default via 192.168.1.1 dev eth0

Common gateway addresses: 192.168.1.1, 192.168.0.1, 10.0.0.1

Log in with your router credentials (often printed on the router's label).

Step 3: Create the Port Forwarding Rule

Look for Port Forwarding, NAT, or Virtual Server in your router's settings. Create a rule with:

FieldExampleNotes
External Port80Port the internet connects to
Internal IP192.168.1.100Your server's LAN IP
Internal Port3000Port your app listens on
ProtocolTCPOr UDP, or Both
DescriptionMy AppOptional label

The external and internal ports can differ. This lets you run an app on port 3000 internally while exposing it as port 80 externally.

Step 4: Test From Outside Your Network

Find your public IP:

curl ifconfig.me
# or visit: whatismyip.com

Test from outside your network (use a phone on mobile data, not the same Wi-Fi):

curl -I http://YOUR_PUBLIC_IP:80

Or use our Port Checker tool to verify the port is accessible from the internet.

Common Port Forwarding Problems

Port still appears closed:

  • Ensure your server is bound to 0.0.0.0 (all interfaces), not just 127.0.0.1
  • Check the server-side firewall (ufw, iptables, Windows Defender) - it may block the port even after router forwarding
  • Some ISPs block port 80 and 443 on residential connections - try port 8080

ISP blocks incoming connections:

  • Some ISPs use CGNAT (Carrier-Grade NAT), giving you a shared public IP that makes port forwarding impossible
  • Solution: Use a tunnel service like Cloudflare Tunnel, ngrok, or Playit.gg

Testing from inside the same network fails:

  • NAT loopback (hairpin NAT) isn't supported by all routers
  • Test from a device on a different network (mobile data)

Server firewall blocking traffic:

Bash
# Allow port 3000 through ufw (Ubuntu)
sudo ufw allow 3000/tcp

# Allow with iptables
sudo iptables -A INPUT -p tcp --dport 3000 -j ACCEPT

TCP vs UDP in Real Applications

HTTP/1.1 and HTTP/2 - TCP

All web traffic uses TCP. The reliability of TCP ensures pages load completely, without missing bytes. HTTP/2 adds multiplexing over a single TCP connection to reduce the overhead of multiple handshakes.

HTTP/3 and QUIC - UDP

HTTP/3 builds on QUIC, which runs over UDP. QUIC reimplements TCP's reliability features at the application layer but avoids TCP's head-of-line blocking problem - if one stream drops a packet, only that stream pauses, not all streams sharing the connection. This is why HTTP/3 is significantly faster for modern web applications.

DNS - UDP (mostly) and TCP

DNS typically uses UDP port 53 for queries (small packets, low overhead). But it falls back to TCP for:

  • Responses larger than 512 bytes
  • Zone transfers between DNS servers
  • DNSSEC-signed responses

Online Gaming - UDP

Games like Fortnite, Valorant, and Counter-Strike use UDP for game state updates (player positions, bullets, etc.). A dropped packet means a slightly stale frame - acceptable. A delayed packet waiting for retransmission would make the game unplayable.

Games typically use a separate TCP connection for reliable data like match results, chat messages, and authentication.

VoIP (WhatsApp, Zoom, Teams) - UDP

Real-time audio uses UDP. The codec handles minor packet loss gracefully - you might hear a slight crackle but the call continues. Using TCP would cause jarring pauses whenever packets needed retransmission.

WebSockets - TCP

WebSockets run over TCP (they start as an HTTP upgrade). If you're building real-time features like chat, live dashboards, or collaborative editing, WebSockets give you a persistent TCP connection with low overhead.

Security Considerations

TCP SYN Flood Attack

Attackers can exploit the TCP handshake by sending thousands of SYN packets without completing the handshake (never sending the final ACK). This fills the server's connection table, causing a DoS. Mitigations include SYN cookies and rate limiting at the firewall.

UDP Amplification Attacks

UDP's connectionless nature makes it vulnerable to reflection/amplification attacks. An attacker sends a small UDP request to a DNS or NTP server with a spoofed source IP (your target). The server sends a much larger response to the victim. Mitigations: rate limiting, source IP validation (BCP38), blocking unused UDP services.

Port Scanning

Both TCP (SYN scan) and UDP scans are used by attackers and security testers to discover open ports. Tools like nmap are standard for security auditing. Keep only necessary ports open and use a firewall to block the rest.

Bash
# Scan TCP ports (requires nmap)
nmap -sT -p 1-1000 192.168.1.1

# Scan UDP ports
nmap -sU -p 53,67,123,161 192.168.1.1

Conclusion

  • TCP: Choose it when data must arrive complete, ordered, and error-free. Web servers, databases, file transfers, email - these all use TCP.
  • UDP: Choose it when speed matters more than perfect delivery. Video streaming, gaming, DNS, VoIP - these all use UDP.
  • ICMP: Not TCP or UDP - it's a diagnostic protocol with no ports. Ping and traceroute use ICMP.
  • Port forwarding: Maps an external port on your router to an internal IP:port so your server is accessible from the internet.

Use our free tools to apply this knowledge:

Related Posts

Best AI Video Editors for Developers

Descript, DaVinci Resolve, Shotstack, Remotion and auto-editor compared for product demos and code-driven video, with prices, licenses and a tested auto-cut.

By DevToolLab Team•

Best HubSpot Alternatives for Developers

HubSpot, Attio, Twenty, Close and EspoCRM compared on published API limits, webhooks, licenses and per-seat prices, plus how long a 50,000-record sync takes.

By DevToolLab Team•

Best Bolt.new Alternatives in 2026

Lovable, v0, Replit, Base44, Dyad, bolt.diy compared on October 2026 prices: tokens versus credits, per-seat versus flat plans, and what a 4-person team pays.

By DevToolLab Team•