Batch 5: Protocols & Security Networking Apache & NGINX Cloud ← Full TOC

🌐 Chapter 43 — Networking

Complete networking reference — OSI model, TCP/IP, IPv4/IPv6, subnetting, DNS, network diagnostics, firewalls, iptables, and WireGuard VPN.
Part of The Direct Path to Linux Ubuntu — free for all.

6Topics
153+Concepts
5Examples
ping/dig/nmapTools
TCP/IP v4+v6Protocols
FreeNo login
📚 OSI Model & TCP/IP 🔢 IP Addressing 📖 DNS 🔧 Network Diagnostics 🔥 Firewalls & iptables 🔒 VPN & WireGuard ⚡ Examples

📚 OSI Model & TCP/IP

📚 OSI Model & TCP/IPOSI 7 layers, TCP/IP stack, protocols at each layer

🔢 IP Addressing

🔢 IP Addressing & SubnettingIPv4, IPv6, CIDR, subnetting, NAT, private ranges

📖 DNS

📖 DNS & Name ResolutionDNS records, resolution process, dig, nslookup, bind

🔧 Network Diagnostics

🔧 Network Diagnosticsping, traceroute, netstat, ss, ip, tcpdump, nmap

🔥 Firewalls & iptables

🔥 Firewalls & iptablesiptables, nftables, ufw, firewalld — packet filtering

🔒 VPN & WireGuard

🔒 VPN & WireGuardWireGuard VPN, OpenVPN, IPsec — secure tunnels

⚡ Quick Examples

Install tools: sudo apt install iproute2 net-tools dnsutils nmap tcpdump traceroute mtr-tiny wireguard iperf3 netcat-openbsd

Network Diagnostics Quick Reference

Essential commands for troubleshooting any network issue.

# ── Connectivity ─────────────────────────────────────────────
ping -c 4 8.8.8.8                  # test basic connectivity
ping -c 4 mywebuniversity.com      # test DNS + connectivity
traceroute mywebuniversity.com     # trace path (UDP)
traceroute -T -p 443 mywebuniversity.com  # TCP trace (firewall-friendly)
mtr --report mywebuniversity.com   # combined ping + trace report

# ── Ports and connections ─────────────────────────────────────
ss -tlnp                           # TCP listening ports + process
ss -ulnp                           # UDP listening ports
ss -anp | grep :443                # connections on port 443
lsof -i :80                        # what's using port 80
nc -zv mywebuniversity.com 443     # test if port is open
nc -zv mywebuniversity.com 22      # test SSH port

# ── Interfaces and routes ─────────────────────────────────────
ip addr show                       # all IPs
ip route show                      # routing table
ip route get 8.8.8.8              # how to reach 8.8.8.8
ip neigh show                      # ARP table

# ── DNS ───────────────────────────────────────────────────────
dig mywebuniversity.com +short     # quick A record
dig mywebuniversity.com MX +short  # mail servers
dig @8.8.8.8 mywebuniversity.com  # query Google DNS
dig +trace mywebuniversity.com    # full resolution trace
host mywebuniversity.com           # simple lookup

# ── Port scan (nmap) ─────────────────────────────────────────
nmap -sV -p 22,80,443 mywebuniversity.com  # top ports + versions
nmap -sn 192.168.1.0/24           # discover hosts on network
sudo nmap -O mywebuniversity.com  # OS detection

# ── Packet capture ────────────────────────────────────────────
sudo tcpdump -i eth0 port 80 -n   # HTTP traffic
sudo tcpdump -i eth0 host 8.8.8.8 # traffic to/from Google
sudo tcpdump -w /tmp/cap.pcap     # save for Wireshark

# ── Bandwidth test ────────────────────────────────────────────
# Server: iperf3 -s
# Client: iperf3 -c server-ip -t 10

# ── HTTP check ────────────────────────────────────────────────
curl -s -o /dev/null -w "HTTP:%{http_code} Time:%{time_total}s\n" https://mywebuniversity.com/
curl -v https://mywebuniversity.com/ 2>&1 | grep -E "^[<>*]" | head -30

IP Subnetting Reference

CIDR subnets, usable hosts, and Python calculator.

# ── CIDR Reference Table ──────────────────────────────────────
# /Prefix  Subnet Mask       Hosts    Notes
# /8       255.0.0.0         16M      Class A
# /16      255.255.0.0       65534    Class B
# /24      255.255.255.0     254      Class C (common)
# /25      255.255.255.128   126      Half a /24
# /26      255.255.255.192   62       Quarter of /24
# /27      255.255.255.224   30       1/8 of /24
# /28      255.255.255.240   14       1/16 of /24 (AWS default)
# /29      255.255.255.248   6        Small
# /30      255.255.255.252   2        Point-to-point links
# /32      255.255.255.255   1 host   Single IP

# ── Private IP Ranges ──────────────────────────────────────────
# 10.0.0.0/8         (10.0.0.0 - 10.255.255.255)    Class A private
# 172.16.0.0/12      (172.16.0.0 - 172.31.255.255)  Class B private
# 192.168.0.0/16     (192.168.0.0 - 192.168.255.255) Class C private
# 127.0.0.0/8        Loopback
# 169.254.0.0/16     Link-local (APIPA / AWS metadata)

# ── Python subnet calculator ──────────────────────────────────
import ipaddress

def subnet_calc(cidr):
    net = ipaddress.IPv4Network(cidr, strict=False)
    hosts = list(net.hosts())
    print(f"Network:    {net}")
    print(f"Netmask:    {net.netmask}")
    print(f"Wildcard:   {net.hostmask}")
    print(f"Network IP: {net.network_address}")
    print(f"Broadcast:  {net.broadcast_address}")
    print(f"First host: {hosts[0] if hosts else 'N/A'}")
    print(f"Last host:  {hosts[-1] if hosts else 'N/A'}")
    print(f"Host count: {len(hosts)}")

subnet_calc("192.168.10.0/24")
subnet_calc("10.0.0.0/8")

# Is IP in subnet?
print(ipaddress.IPv4Address("192.168.1.100") in ipaddress.IPv4Network("192.168.1.0/24"))  # True

# Divide into subnets
net = ipaddress.IPv4Network("10.0.0.0/24")
for s in net.subnets(new_prefix=26):
    print(f"  {s}  hosts={s.num_addresses-2}")

# Aggregate routes
nets = [ipaddress.IPv4Network(n) for n in ["192.168.1.0/24","192.168.2.0/24","192.168.3.0/24","192.168.0.0/24"]]
print("Aggregated:", list(ipaddress.collapse_addresses(nets)))

DNS Troubleshooting

Diagnose DNS issues with dig, nslookup, and Python.

# ── dig cheatsheet ────────────────────────────────────────────
dig mywebuniversity.com              # A record
dig mywebuniversity.com AAAA         # IPv6
dig mywebuniversity.com MX           # mail servers
dig mywebuniversity.com TXT          # SPF, DKIM, verification
dig mywebuniversity.com NS           # name servers
dig mywebuniversity.com SOA          # zone info
dig -x 203.0.113.10                  # reverse DNS (PTR)
dig +short mywebuniversity.com       # just the IP
dig +trace mywebuniversity.com       # full resolution trace
dig @8.8.8.8 mywebuniversity.com    # use Google DNS
dig @1.1.1.1 mywebuniversity.com    # use Cloudflare DNS

# Check if DNS is propagated globally
dig @8.8.8.8   mywebuniversity.com +short  # Google
dig @1.1.1.1   mywebuniversity.com +short  # Cloudflare
dig @9.9.9.9   mywebuniversity.com +short  # Quad9
dig @208.67.222.222 mywebuniversity.com +short  # OpenDNS

# Check DMARC, SPF, DKIM
dig TXT mywebuniversity.com +short          # SPF record
dig TXT _dmarc.mywebuniversity.com +short   # DMARC policy
dig TXT default._domainkey.mywebuniversity.com  # DKIM

# ── Python DNS query ──────────────────────────────────────────
# pip install dnspython
import dns.resolver

def dns_lookup(domain, rtype='A'):
    try:
        answers = dns.resolver.resolve(domain, rtype)
        return [str(r) for r in answers]
    except dns.resolver.NXDOMAIN:
        return ["NXDOMAIN — domain does not exist"]
    except dns.resolver.NoAnswer:
        return [f"No {rtype} records found"]
    except Exception as e:
        return [f"Error: {e}"]

domain = "mywebuniversity.com"
for rtype in ['A','AAAA','MX','NS','TXT']:
    results = dns_lookup(domain, rtype)
    for r in results:
        print(f"  {rtype:6}: {r[:70]}")

# Check DNS propagation
for server in ['8.8.8.8','1.1.1.1','9.9.9.9']:
    resolver = dns.resolver.Resolver()
    resolver.nameservers = [server]
    try:
        ip = resolver.resolve(domain, 'A')[0].address
        print(f"  {server} -> {ip}")
    except Exception as e:
        print(f"  {server} -> ERROR: {e}")
# python3 dns_check.py

WireGuard VPN Quick Setup

Set up a WireGuard VPN server and client in minutes.

#!/bin/bash
# WireGuard VPN Quick Setup — Server side
# Run on Ubuntu 22.04/24.04 server

# Install
sudo apt update && sudo apt install -y wireguard wireguard-tools qrencode

# Generate server keys
wg genkey | sudo tee /etc/wireguard/private.key > /dev/null
sudo chmod 600 /etc/wireguard/private.key
sudo cat /etc/wireguard/private.key | wg pubkey | sudo tee /etc/wireguard/public.key
echo "Server public key: $(sudo cat /etc/wireguard/public.key)"

# Generate client keys
wg genkey | tee /tmp/client.key | wg pubkey > /tmp/client.pub
echo "Client public key: $(cat /tmp/client.pub)"

# Get network interface
IFACE=$(ip route show default | awk '/default/ {print $5}' | head -1)
echo "Default interface: $IFACE"

# Server config
sudo tee /etc/wireguard/wg0.conf << EOF
[Interface]
PrivateKey = $(sudo cat /etc/wireguard/private.key)
Address    = 10.10.0.1/24
ListenPort = 51820
PostUp     = echo 1 > /proc/sys/net/ipv4/ip_forward && iptables -A FORWARD -i wg0 -j ACCEPT && iptables -t nat -A POSTROUTING -o $IFACE -j MASQUERADE
PostDown   = iptables -D FORWARD -i wg0 -j ACCEPT; iptables -t nat -D POSTROUTING -o $IFACE -j MASQUERADE

[Peer]
# Client: Alice's laptop
PublicKey  = $(cat /tmp/client.pub)
AllowedIPs = 10.10.0.2/32
EOF

# Client config
cat > /tmp/client-wg0.conf << EOF
[Interface]
PrivateKey = $(cat /tmp/client.key)
Address    = 10.10.0.2/24
DNS        = 1.1.1.1

[Peer]
PublicKey           = $(sudo cat /etc/wireguard/public.key)
Endpoint            = $(curl -s ifconfig.me 2>/dev/null || echo "YOUR_SERVER_IP"):51820
AllowedIPs          = 0.0.0.0/0, ::/0
PersistentKeepalive = 25
EOF

# Start WireGuard
sudo wg-quick up wg0
sudo systemctl enable wg-quick@wg0

# Show QR code for mobile app
echo "=== Scan with WireGuard mobile app ==="
qrencode -t ansiutf8 < /tmp/client-wg0.conf

# Show client config
echo "=== Client config file ==="
cat /tmp/client-wg0.conf

# Status
sudo wg show

# UFW: allow WireGuard port
sudo ufw allow 51820/udp comment 'WireGuard'

echo "Done! Copy /tmp/client-wg0.conf to client and run: sudo wg-quick up client-wg0.conf

Firewall with ufw and iptables

Configure Linux firewall for a web server.

#!/bin/bash
# Firewall setup for MyWebUniversity web server
# Allows: SSH, HTTP, HTTPS. Blocks everything else.

# ── UFW (Ubuntu — recommended) ────────────────────────────────
sudo ufw default deny incoming   # block all inbound by default
sudo ufw default allow outgoing  # allow all outbound

# Core services
sudo ufw allow 22/tcp    comment 'SSH'
sudo ufw allow 80/tcp    comment 'HTTP'
sudo ufw allow 443/tcp   comment 'HTTPS'

# Rate limit SSH (blocks brute force)
sudo ufw limit 22/tcp

# Allow PostgreSQL only from specific IP
sudo ufw allow from 10.0.1.10 to any port 5432 proto tcp comment 'PostgreSQL from app server'

# Block common attack ports
sudo ufw deny 3306/tcp   comment 'Block MySQL from internet'
sudo ufw deny 6379/tcp   comment 'Block Redis from internet'
sudo ufw deny 27017/tcp  comment 'Block MongoDB from internet'

# Enable and check
sudo ufw --force enable
sudo ufw status verbose
sudo ufw status numbered

# Delete a rule by number
# sudo ufw delete 5

# ── iptables (any Linux) ──────────────────────────────────────
# Reset
sudo iptables -F && sudo iptables -X

# Default: drop all inbound, allow all outbound
sudo iptables -P INPUT DROP
sudo iptables -P OUTPUT ACCEPT
sudo iptables -P FORWARD DROP

# Allow loopback and established connections
sudo iptables -A INPUT -i lo -j ACCEPT
sudo iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT

# Allow SSH (rate limited)
sudo iptables -A INPUT -p tcp --dport 22 -m conntrack --ctstate NEW   -m limit --limit 3/min --limit-burst 10 -j ACCEPT

# Allow HTTP and HTTPS
sudo iptables -A INPUT -p tcp --dport 80  -m conntrack --ctstate NEW -j ACCEPT
sudo iptables -A INPUT -p tcp --dport 443 -m conntrack --ctstate NEW -j ACCEPT

# Allow ICMP ping (limited)
sudo iptables -A INPUT -p icmp --icmp-type echo-request   -m limit --limit 1/s --limit-burst 5 -j ACCEPT

# Log and drop everything else
sudo iptables -A INPUT -j LOG --log-prefix "DROPPED: " --log-level 6
sudo iptables -A INPUT -j DROP

# Save (Ubuntu)
sudo apt install -y iptables-persistent
sudo iptables-save > /etc/iptables/rules.v4
echo "Firewall configured!"
sudo iptables -L -n --line-numbers