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.
| Feature | TCP | UDP |
|---|---|---|
| Connection | 3-way handshake required | None - connectionless |
| Delivery guarantee | Yes - retransmits lost packets | No guarantee |
| Ordering | Data arrives in order | Packets may arrive out of order |
| Error correction | Full | Checksum only |
| Speed | Slower (more overhead) | Faster (minimal overhead) |
| Header size | 20–60 bytes | 8 bytes (fixed) |
| Flow control | Yes - sliding window | None |
| Congestion control | Yes - backs off under load | None |
| Broadcast/Multicast | No | Yes |
| Best for | Web, databases, email, file transfer | Streaming, 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:
- SYN - Client sends a synchronize packet: "I want to connect"
- SYN-ACK - Server replies: "OK, I'm ready"
- 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:
- Client sends FIN (finished)
- Server sends ACK
- Server sends its own FIN
- 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.
BashUDP 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
- Your machine sends an ICMP Echo Request packet to the destination
- The destination replies with an ICMP Echo Reply
- Your machine measures the round-trip time
The output looks like this:
BashPING 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.
Bashtraceroute 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
| Port | Protocol | Service | Description |
|---|---|---|---|
| 20 | TCP | FTP Data | FTP active mode data transfer |
| 21 | TCP | FTP Control | FTP command and control |
| 22 | TCP | SSH | Encrypted remote access and tunneling |
| 23 | TCP | Telnet | Unencrypted terminal (obsolete - use SSH) |
| 25 | TCP | SMTP | Email delivery between servers |
| 53 | TCP/UDP | DNS | Domain name lookups |
| 67/68 | UDP | DHCP | Dynamic IP address assignment |
| 69 | UDP | TFTP | Trivial file transfer, used in PXE boot |
| 80 | TCP | HTTP | Unencrypted web traffic |
| 110 | TCP | POP3 | Email retrieval (legacy) |
| 123 | UDP | NTP | Network time synchronization |
| 143 | TCP | IMAP | Email inbox access and sync |
| 161/162 | UDP | SNMP | Network device monitoring |
| 179 | TCP | BGP | Internet routing protocol |
| 389 | TCP/UDP | LDAP | Directory services and authentication |
| 443 | TCP | HTTPS | Encrypted web traffic (TLS) |
| 445 | TCP | SMB | Windows file sharing |
| 465/587 | TCP | SMTPS/Submission | Secure email sending |
| 636 | TCP | LDAPS | Secure LDAP over TLS |
| 993 | TCP | IMAPS | Secure IMAP over TLS |
| 995 | TCP | POP3S | Secure POP3 over TLS |
Database & Cache Ports
| Port | Protocol | Service | Description |
|---|---|---|---|
| 1433 | TCP | MSSQL | Microsoft SQL Server |
| 1521 | TCP | Oracle DB | Oracle Database listener |
| 3306 | TCP | MySQL / MariaDB | Most popular open-source relational DB |
| 5432 | TCP | PostgreSQL | Advanced open-source relational DB |
| 5984 | TCP | CouchDB | Document database with REST API |
| 6379 | TCP | Redis | In-memory cache and message broker |
| 9200 | TCP | Elasticsearch | Search and analytics engine HTTP API |
| 11211 | TCP/UDP | Memcached | Distributed memory caching |
| 27017 | TCP | MongoDB | NoSQL document database |
DevOps & Messaging Ports
| Port | Protocol | Service | Description |
|---|---|---|---|
| 2375 | TCP | Docker (no TLS) | Docker daemon REST API (unencrypted) |
| 2376 | TCP | Docker (TLS) | Docker daemon REST API (encrypted) |
| 3389 | TCP/UDP | RDP | Windows Remote Desktop |
| 4369 | TCP | Erlang EPM | Used by RabbitMQ node discovery |
| 5672 | TCP | AMQP (RabbitMQ) | Message queue protocol |
| 5671 | TCP | AMQPS | Secure AMQP over TLS |
| 6443 | TCP | Kubernetes API | kube-apiserver |
| 8080 | TCP | HTTP Alt | Dev servers, proxies, Tomcat |
| 9090 | TCP | Prometheus | Metrics and alerting |
| 9092 | TCP | Apache Kafka | Message broker |
| 15672 | TCP | RabbitMQ UI | Web management console |
Development Server Ports
| Port | Protocol | Service | Description |
|---|---|---|---|
| 3000 | TCP | React / Next.js / Node.js | Most popular dev server port |
| 3001 | TCP | React fallback / Remix | When 3000 is occupied |
| 4200 | TCP | Angular CLI | Angular dev server |
| 4321 | TCP | Astro | Astro dev server |
| 5173 | TCP | Vite | Vite-based dev servers |
| 8000 | TCP | Django / FastAPI | Python web frameworks |
| 8888 | TCP | Jupyter Notebook | Data science notebooks |
| 11434 | TCP | Ollama | Local 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:
Baship addr show # Linux ifconfig # macOS # Look for inet 192.168.x.x under your active interface (eth0, en0, wlan0)
Windows:
cmdipconfig # 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:
| Field | Example | Notes |
|---|---|---|
| External Port | 80 | Port the internet connects to |
| Internal IP | 192.168.1.100 | Your server's LAN IP |
| Internal Port | 3000 | Port your app listens on |
| Protocol | TCP | Or UDP, or Both |
| Description | My App | Optional 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 just127.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:
- Port Checker - check if a port is open from the internet
- DNS Lookup - verify DNS records
- Localhost Port Tester - look up what runs on any localhost port
- Browser Error Codes - diagnose connection and SSL errors
