Linux: Networking Basics
Linux networking commands are essential tools for diagnosing "why can't I connect." From viewing IPs to testing port connectivity, from DNS resolution to HTTP requests — these commands cover the full network troubleshooting process.
📋 Prerequisites: You should already know
- Lesson 3: Terminal Basics
1. What You'll Learn
- ip addr/route: view network configuration
- ping/mtr: connectivity testing
- curl/wget: HTTP requests
- ss/netstat: port listening
- dig: DNS queries
2. A Story of "Website Won't Load"
(1) The Pain Point: Deployed a Service but It's Not Accessible Externally
Xiaoming deployed a Node.js service on port 3000, but accessing http://server-ip:3000 from a browser kept timing out.
He verified locally first:
curl http://localhost:3000
# ✅ Returns HTML normally
Then checked from outside:
# Check if the port is listening
ss -tlnp | grep 3000
# LISTEN 0 128 127.0.0.1:3000 0.0.0.0:* ← Only listening on localhost!
# Node.js bound to 127.0.0.1 instead of 0.0.0.0
(2) Fix the Bind Address
Xiaoming changed server.listen(3000, '127.0.0.1') to server.listen(3000, '0.0.0.0'). After restarting, external access worked.
PermitRootLogin no to disable direct root SSH login, using a regular user + sudo instead. Also disable password login (PasswordAuthentication no) and use key authentication only.
(3) The Benefit: A Systematic Troubleshooting Approach
Xiaoming learned the troubleshooting sequence: curl locally to confirm the service works → ss to check the listening address → check the firewall → curl externally to verify.
3. Knowledge Points
(1) ip — Network Configuration
# View IP addresses
ip addr show
# Or shorthand
ip a
# View routing table
ip route
# Or shorthand
ip r
# View network interface status
ip link show
# Enable/disable interface
sudo ip link set eth0 up
sudo ip link set eth0 down
(2) ping/mtr — Connectivity Testing
# ping (test network connectivity)
ping google.com # Continuous ping, Ctrl+C to stop
ping -c 4 google.com # Ping only 4 times
ping -c 4 -i 2 google.com # 2-second interval
ping -c 10 -q google.com # Summary only
# mtr (combines traceroute and ping)
mtr google.com # Continuously trace route
mtr -r -c 10 google.com # Report mode (output after 10 rounds)
(3) curl/wget — HTTP Requests
# curl (HTTP requests)
curl https://example.com # GET request
curl -I https://example.com # Headers only
curl -o page.html https://example.com # Save to file
> 💡 Tip: `curl -v` (verbose mode) is a powerful tool for debugging HTTP issues — it shows the complete request headers, response headers, and TLS handshake process, helping you pinpoint whether it's a DNS issue, connection timeout, certificate error, or redirect problem. When a `curl` request fails, your first step should be adding `-v` for details.
curl -L http://httpbin.org/redirect/3 # Follow redirects
curl -k https://self-signed.com # Skip SSL verification
curl -X POST -d '{"key":"value"}' -H "Content-Type: application/json" https://api.example.com
# wget (file download)
wget https://example.com/file.zip # Download file
wget -c https://example.com/big.zip # Resume download
wget -r -np https://example.com/docs/ # Recursive download
(4) ss/netstat — Port Listening
# ss (recommended, faster)
ss -tlnp # TCP listening ports
ss -ulnp # UDP listening ports
ss -tlnp | grep 80 # Filter port 80
ss -tuna # All TCP/UDP connections
# netstat (traditional, may need install)
netstat -tlnp
netstat -i # Network interface statistics
(5) dig — DNS Queries
# dig
dig example.com # Full DNS query
dig +short example.com # IP only
dig example.com A # Query A record
dig example.com MX # Query mail record
dig @8.8.8.8 example.com # Use specific DNS server
# Other DNS tools
nslookup example.com # Simple query
host example.com # More concise
ℹ️ Note:
dig,nslookup, andhostcan all query DNS records but have different output formats —digis the most detailed (includes query time, server, etc.),nslookupis more concise, andhostis the most minimal (IP only). Usedigfor DNS troubleshooting,hostordig +shortfor quick IP lookups.
(6) ▶ Example: View Local Network Configuration
# View all IP addresses
ip -br addr
# lo UNKNOWN 127.0.0.1/8
# eth0 UP 192.168.1.100/24
# View default gateway
ip route | grep default
# default via 192.168.1.1 dev eth0
# View DNS
cat /etc/resolv.conf
# nameserver 8.8.8.8
# nameserver 1.1.1.1
Output:
TEXTlo UNKNOWN 127.0.0.1/8 eth0 UP 192.168.1.100/24 default via 192.168.1.1 dev eth0 nameserver 8.8.8.8 nameserver 1.1.1.1
(7) ▶ Example: Network Connectivity Troubleshooting
# 1. Ping the gateway first (confirm LAN works)
ping -c 2 192.168.1.1
# 2. Ping an external IP (confirm internet works)
ping -c 2 8.8.8.8
# 3. DNS resolution (confirm domain resolution works)
dig +short google.com
# 4. Port connectivity (confirm service port is open)
nc -zv google.com 80
# Connection to google.com (142.250.80.14) 80 port [tcp/http] succeeded!
# 5. HTTP request (confirm service is working)
curl -I https://example.com
Output:
TEXTPING 192.168.1.1 (192.168.1.1) 56(84) bytes of data. 64 bytes from 192.168.1.1: icmp_seq=1 ttl=64 time=0.423 ms --- 192.168.1.1 ping statistics --- 2 packets transmitted, 2 received, 0% packet loss PING 8.8.8.8 (8.8.8.8) 56(84) bytes of data. 64 bytes from 8.8.8.8: icmp_seq=1 ttl=118 time=12.3 ms --- 8.8.8.8 ping statistics --- 2 packets transmitted, 2 received, 0% packet loss 142.250.80.14 Connection to google.com (142.250.80.14) 80 port [tcp/http] succeeded! HTTP/1.1 200 OK Content-Type: text/html; charset=UTF-8 Server: ECS (dcb/7F84)
(8) ▶ Example: curl Testing APIs
# GET request
curl https://api.github.com/users/octocat
# View response headers
curl -I https://httpbin.org
# POST JSON data
curl -X POST https://httpbin.org/post \
-H "Content-Type: application/json" \
-d '{"name":"Alice","role":"developer"}'
# Authenticated request
curl -u "username:token" https://api.github.com/user
# Test HTTP status code
curl -s -o /dev/null -w "%{http_code}" https://example.com
Output:
TEXT{"login":"octocat","id":583231,"avatar_url":"https://avatars.githubusercontent.com/u/583231?v=4"} HTTP/1.1 200 OK Server: gunicorn/19.9.0 Content-Type: application/json { "json": { "name": "Alice", "role": "developer" } } 200
(9) ▶ Example: Port Troubleshooting
# View all listening TCP ports
ss -tlnp
# Check if port 3306 (MySQL) is listening
ss -tlnp | grep 3306
# View ports for a specific process
ss -tlnp | grep nginx
# Test if a remote port is open
echo "Testing port 80..."
timeout 3 bash -c "echo >/dev/tcp/example.com/80" && echo "Open" || echo "Closed"
# View connection states
ss -tuna | grep ESTAB
Output:
TEXTState Recv-Q Send-Q Local Address:Port Peer Address:Port Process LISTEN 0 128 0.0.0.0:22 0.0.0.0:* LISTEN 0 128 0.0.0.0:80 0.0.0.0:* LISTEN 0 128 0.0.0.0:443 0.0.0.0:* LISTEN 0 128 *:3306 *:* LISTEN 0 511 *:80 *:* users:(("nginx",pid=1234,fd=6)) Open ESTAB 0 0 192.168.1.100:22 10.0.0.50:52341 ESTAB 0 0 192.168.1.100:443 172.16.0.5:49832
(10) ▶ Example: Downloading Files
# wget download
wget -c https://releases.ubuntu.com/22.04/ubuntu-22.04.3-live-server-amd64.iso
# curl download
curl -L -o ubuntu.iso https://releases.ubuntu.com/22.04/ubuntu-22.04.3-live-server-amd64.iso
# Download and extract
curl -L https://github.com/user/repo/archive/main.tar.gz | tar -xz
Output:
TEXT--2026-07-07 10:23:01-- https://releases.ubuntu.com/22.04/ubuntu-22.04.3-live-server-amd64.iso Resolving releases.ubuntu.com... 185.125.190.37 HTTP request sent, awaiting response... 200 OK Length: 2014838784 (1.9G) [application/x-iso9660-image] Saving to: 'ubuntu-22.04.3-live-server-amd64.iso' % Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed 45% 891M 0 0 891M 0 0 12.3M 0:00:02 0:00:01 0:00:01 12.3M
(11) ▶ Comprehensive Example: Network Diagnostics Script
#!/bin/bash
# net-diag.sh - Network diagnostics tool
TARGET="${1:-google.com}"
echo "========================================"
echo " Network Diagnostics Report"
echo " Time: $(date)"
echo "========================================"
echo ""
echo "1. Local Network Configuration"
echo "----------------"
ip -br addr 2>/dev/null || ifconfig
echo ""
echo "2. Default Gateway"
echo "-----------"
ip route | grep default
echo ""
echo "3. DNS Servers"
echo "--------------"
cat /etc/resolv.conf | grep nameserver
echo ""
echo "4. DNS Resolution ($TARGET)"
echo "----------------------"
dig +short "$TARGET" 2>/dev/null || nslookup "$TARGET" 2>/dev/null || host "$TARGET"
echo ""
echo "5. Network Connectivity"
echo "--------------"
ping -c 4 -q "$TARGET" 2>&1 | tail -3
echo ""
echo "6. HTTP Response"
echo "-------------"
curl -s -o /dev/null -w "HTTP %{http_code}, time: %{time_total}s\n" "https://$TARGET" --connect-timeout 5
echo ""
echo "7. Route Tracing"
echo "------------"
mtr -r -c 3 "$TARGET" 2>/dev/null | tail -5 || echo "mtr not installed"
echo ""
echo "8. Listening Ports"
echo "-----------"
ss -tlnp 2>/dev/null | head -10 || netstat -tlnp 2>/dev/null | head -10
echo ""
echo "========================================"
❓ FAQ
Q: If ping fails, is it always a network problem? A: Not necessarily. Many servers firewall ICMP (ping). It's completely normal for ping to fail but HTTP to work. Alternative:
nc -zv host portorcurl -Ito test specific service ports.
Q: What's the difference between curl and wget? A: curl is more feature-rich (supports all HTTP methods, custom headers, JSON data), ideal for API testing. wget has stronger download capabilities (recursive download, resume, site mirroring). Use curl for daily API testing, wget for file downloads.
Q: Which is better, ss or netstat? A: ss is newer and faster — it reads directly from the kernel socket buffer without parsing /proc/net. netstat is older and slower on systems with many connections. Prefer ss; netstat may not be installed by default on newer systems.
Q: What's the difference between port 80 and 443? A: 80 is HTTP (plaintext), 443 is HTTPS (encrypted). Modern websites basically only use 443. If
curl http://...doesn't work, trycurl https://....
Q: Why is SSH connection slow? A: Common causes: 1) DNS reverse lookup (configure
UseDNS no). 2) GSSAPI authentication (configureGSSAPIAuthentication no). 3) Network latency. Quick fix: addUseDNS noandGSSAPIAuthentication noto~/.ssh/config.
📖 Summary
ip addr/ip routeview IP and routingping -c 4test connectivity,mtrtrace routecurl -Iview response headers,curl -X POST -d '{}'send requestsss -tlnpview listening portsdig +shortquick DNS query
📝 Exercises
- Basic (⭐): Use
ip -br addrto view your local IP and network interfaces, then useping -c 4 google.comto test connectivity and analyze the results - Intermediate (⭐⭐): Use
ss -tlnpto view all listening ports on your machine, then usecurl -I https://example.comto view HTTP response headers, anddig +short github.comto query GitHub's IP address - Challenge (⭐⭐⭐): Write a network diagnostics script that automatically detects local IP, gateway, DNS, connectivity, HTTP response, and listening ports, outputs a formatted report, and highlights warnings in color when anomalies are detected