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

1. What You'll Learn


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:

BASH
curl http://localhost:3000
# ✅ Returns HTML normally

Then checked from outside:

BASH
# 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.

⚠️ Warning: SSH services default to allowing root user direct login — this is the most common security vulnerability. Production servers must set 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

BASH
# 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

TEXT
# 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

BASH
# 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

BASH
# 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

TEXT
# 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, and host can all query DNS records but have different output formats — dig is the most detailed (includes query time, server, etc.), nslookup is more concise, and host is the most minimal (IP only). Use dig for DNS troubleshooting, host or dig +short for quick IP lookups.

(6) ▶ Example: View Local Network Configuration

BASH
# 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:

TEXT
lo               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

BASH
# 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:

TEXT
PING 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

BASH
# 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

BASH
# 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:

TEXT
State   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

BASH
# 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

BASH
#!/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 port or curl -I to 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, try curl https://....

Q: Why is SSH connection slow? A: Common causes: 1) DNS reverse lookup (configure UseDNS no). 2) GSSAPI authentication (configure GSSAPIAuthentication no). 3) Network latency. Quick fix: add UseDNS no and GSSAPIAuthentication no to ~/.ssh/config.


📖 Summary


📝 Exercises

  1. Basic (⭐): Use ip -br addr to view your local IP and network interfaces, then use ping -c 4 google.com to test connectivity and analyze the results
  2. Intermediate (⭐⭐): Use ss -tlnp to view all listening ports on your machine, then use curl -I https://example.com to view HTTP response headers, and dig +short github.com to query GitHub's IP address
  3. 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
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏