# Networking: addresses, DNS, routes and SSH

IP addresses, ports and subnets, how names become addresses, where packets are routed, DHCP and static IPs, SSH with keys, and copying files with scp and rsync.

Course: [Linux & Bash for DevOps](https://devops.rajeev.pro/courses/linux), lesson 13. About 45 minutes, intermediate. Source: https://devops.rajeev.pro/courses/linux/13-networking

## What you will learn

- Explain IP addresses, ports, TCP and UDP, and read ip addr and ip route
- Work out a subnet's range from its CIDR, such as 10.0.1.0/24
- Follow a name lookup through /etc/hosts and DNS, and debug it with getent and dig
- Read the routing table and find which route a packet takes
- Tell DHCP from a static address, and set one with netplan
- Log in with SSH keys, harden sshd, and use ~/.ssh/config
- Copy files with scp, and sync folders with rsync

## What happens when you curl a URL

**Why networking feels hard.** "The site is down" can mean a dozen different things: the name doesn't
resolve, the server is unreachable, a firewall drops the traffic, nothing is listening on the port,
the certificate is wrong, or the app itself is returning errors. People who are new to it try random
fixes. People who are good at it know the order the connection is built in, and check each step until
one fails.

When you run `curl https://example.com`, five things happen in order:

1. **Name to address (DNS).** Your machine asks "what's the IP of example.com?" and gets an address.
2. **Which way to send it (routing).** It checks its routing table: is that address on my own network,
   or do I send it to the gateway?
3. **Connect (TCP).** It opens a connection to port 443 on that address. The server answers only if
   something is listening and no firewall is in the way.
4. **Encrypt (TLS).** The two sides agree on encryption, and the server proves its identity with a
   certificate.
5. **Talk (HTTP).** curl sends the request, and the app sends back a response.

Every networking problem is a failure at one of these steps. Learn the steps and you know what to
check:

> **Figure.** Animated. curl https://example.com runs on the server. First the name is resolved: the question goes to the DNS server from /etc/resolv.conf and the answer 172.66.147.243 comes back. Next the routing table sends the packet to the default gateway 172.29.80.1, because the address is outside the local subnet. The packet crosses the internet and the remote firewall to port 443, where nginx is listening, and the reply comes back: HTTP 200. Stops at step 1 mean DNS, at 2 no route, a timeout at 3 a firewall, and refused at 4 nothing listening.
>
> Name, route, port, program. Test the steps in order and the broken one shows itself.

## TCP/IP: addresses, ports and layers

An **IP address** finds the machine. A **port** finds the program on it. A connection is the pair
`address:port` at each end, such as `172.29.94.205:51544 → 93.184.215.14:443`.

| Layer       | Does                                          | You see                 |
| ----------- | --------------------------------------------- | ----------------------- |
| Application | The conversation itself                       | HTTP, DNS, SSH          |
| Transport   | Ports; reliable (TCP) or quick (UDP) delivery | `:443/tcp`, `:53/udp`   |
| Internet    | Addresses and routing between networks        | `10.0.1.15`, `ip route` |
| Link        | The local network card and its neighbours     | `eth0`, MAC addresses   |

**TCP** sets up a connection and makes sure every byte arrives in order (web, SSH, databases).
**UDP** sends packets with no setup or guarantee (DNS, video calls). Ports you'll meet every day:
22 SSH, 53 DNS, 80 HTTP, 443 HTTPS, 5432 PostgreSQL, 3306 MySQL, 6379 Redis.

```sh
$ ip -br addr                    # your interfaces and addresses, one line each
lo               UNKNOWN        127.0.0.1/8 ::1/128
eth0             UP             172.29.94.205/20 fe80::215:5dff:fe72:6be6/64
$ ip link                        # interfaces, state and MAC addresses
```

`lo` is the loopback: `127.0.0.1` is this machine talking to itself. An app listening only on
`127.0.0.1` can't be reached from outside, which is the right setting for a database the app shares
a machine with.

## Subnets and CIDR

Think of an IP address like a postal address. The first part names the **street** (the network)
and the rest names the **house** on that street (the host). Houses on the same street can hand
things to each other directly. For any other street, you give the letter to the post office (the
**router**, or gateway) and it works out the way. CIDR notation is just a way of saying where the
street name ends.

`172.29.94.205/20` is an address _and_ its network. The `/20` says how many leading bits name the
network; the rest number the hosts. Machines in the same subnet talk directly; anything else goes
through a router.

| CIDR  | Netmask         | Addresses  | Typical use                                 |
| ----- | --------------- | ---------- | ------------------------------------------- |
| `/32` | 255.255.255.255 | 1          | one host, in firewall rules                 |
| `/28` | 255.255.255.240 | 16         | a tiny subnet                               |
| `/26` | 255.255.255.192 | 64         |                                             |
| `/24` | 255.255.255.0   | 256        | a common subnet: `10.0.1.0` to `10.0.1.255` |
| `/16` | 255.255.0.0     | 65,536     | a whole cloud network (VPC)                 |
| `/0`  | 0.0.0.0         | everything | "any address", the default route            |

Each step of one in the prefix halves the size: a /25 is half a /24. The first address is the
network and the last the broadcast, so a /24 has 254 usable hosts. **Private ranges**, which are never
routed on the internet, are `10.0.0.0/8`, `172.16.0.0/12` and `192.168.0.0/16`. Any network may reuse
them, which is fine until two networks need to talk: if your office and your cloud VPC both use
`10.0.0.0/16`, a VPN between them can't tell which side an address belongs to. Plan ranges that
don't overlap before you connect networks.

Use a prefix that leaves enough addresses for current hosts and expected growth. `/32` is useful for one
address in an allowlist; `/0` matches every IPv4 destination and is commonly used for a default route. A
common mistake is assuming a private address is secure by itself: routing and firewall rules still determine
which systems can communicate.

## DNS: from a name to an address

People use names, but network packets need addresses. DNS lets applications find the current record without
hard-coding an IP into every config file. Linux name lookup may consult local files and resolver services
before asking an upstream DNS server.

```text
program → /etc/nsswitch.conf ("hosts: files dns")
        → /etc/hosts               fixed names, checked first
        → /etc/resolv.conf         which DNS server to ask (often 127.0.0.53, systemd-resolved)
        → DNS server               answers, or asks the internet's DNS for you
```

```sh
$ getent ahostsv4 example.com     # look up a name exactly as programs do
172.66.147.243  STREAM example.com
$ cat /etc/resolv.conf            # which DNS server this machine asks
$ resolvectl status               # systemd-resolved: the real upstream servers
$ dig example.com +short          # ask DNS directly (package dnsutils or bind-utils)
$ dig @1.1.1.1 example.com        # ask a specific server: is it my DNS or the record?
```

Records you'll use: **A** (name → IPv4), **AAAA** (→ IPv6), **CNAME** (name → another name),
**MX** (mail), **TXT** (verification, SPF). DNS answers are cached for their **TTL**, which is why a
changed record can take minutes or hours to reach everyone.

Use `getent` to see what your app sees, since it follows `/etc/hosts` too. Use `dig` to see what DNS
says. When they disagree, something in `/etc/hosts` is overriding DNS.

Use `getent` to test the system's normal lookup path, and `dig` to query DNS records directly. Check the TTL
before expecting a changed record to appear everywhere; caches can keep an old answer until it expires. A
common mistake is changing DNS and repeatedly testing one cached result without checking the authoritative
answer or local resolver cache.

> **Video.** [How to Use the dig Command in Linux | DNS Lookup Tutorial](https://www.youtube.com/watch?v=_6aL4m8aDjc&t=223s) (Learn Linux TV)

## Routing: where packets go

An IP packet needs a next hop. The routing table compares its destination with configured network prefixes
and selects the most specific match. If no specific route matches, the **default route** sends it to a
gateway, which may know how to reach other networks.

```sh
$ ip route
default via 172.29.80.1 dev eth0 proto kernel
172.29.80.0/20 dev eth0 proto kernel scope link src 172.29.94.205
$ ip route get 1.1.1.1            # which route this destination takes
1.1.1.1 via 172.29.80.1 dev eth0 src 172.29.94.205 uid 1000
```

Read it bottom-up: anything in `172.29.80.0/20` is local, sent straight out of `eth0`. Everything
else matches `default` and goes to the **gateway** `172.29.80.1`. When several routes match, the most
specific one (longest prefix) wins. A server with no default route can talk to its subnet and
nothing else.

```sh
$ sudo ip route add 10.20.0.0/16 via 172.29.80.5   # until reboot: reach another network via .5
$ sudo ip route del 10.20.0.0/16
```

`ip route get` shows the route the kernel would choose for a destination, including its outgoing interface
and source address. Routes added with `ip route add` are temporary and usually disappear on reboot; persistent
routes belong in the network manager's configuration. A common mistake is adding a route to the wrong
gateway or interface and assuming connectivity will recover without checking the selected path.

> **Video.** [How to Use the ip Command in Linux: A Beginner’s Guide](https://www.youtube.com/watch?v=wHfIFZlDxtU) (Learn Linux TV)

## DHCP and static addresses

Most servers use **Dynamic Host Configuration Protocol (DHCP)**. At startup, the client asks the network for
an address, prefix, gateway and DNS configuration. A DHCP server grants a lease, which the client renews
before it expires. This avoids manually configuring every machine, but an unexpected or duplicate lease can
break reachability.

For a fixed address, use a reservation or a managed network configuration so the address remains unique. In
cloud networks, keep provider DHCP enabled and assign a stable private address through the cloud console or
API rather than overriding the guest network settings.

For a fixed address on Ubuntu, describe it in **netplan**:

```yaml
# /etc/netplan/60-static.yaml
network:
  version: 2
  ethernets:
    eth0:
      dhcp4: false
      addresses: [10.0.1.15/24]
      routes:
        - to: default
          via: 10.0.1.1
      nameservers:
        addresses: [1.1.1.1, 8.8.8.8]
```

```sh
$ sudo netplan try               # applies it, and rolls back after 120 s unless you confirm
$ sudo netplan apply
```

> **Use netplan try on remote servers.** A wrong network config over SSH cuts the connection you need to fix it. `netplan try` reverts automatically if you can't press Enter to confirm. RHEL-family systems use NetworkManager (`nmcli`) instead.

Use DHCP for ordinary cloud instances and static settings only when the network design requires them. A
mistyped address, gateway or DNS server can disconnect a remote host. On Ubuntu, `netplan try` applies a
change temporarily and rolls it back unless confirmed; still keep a console recovery path ready. A common
mistake is applying a remote network change without testing it in a second session.

## SSH with keys

SSH logs you into a remote server over an encrypted connection. Keys beat passwords: there's
nothing to guess, and a key never leaves your laptop.

```sh
$ ssh-keygen -t ed25519 -C "rajeev@laptop"     # makes ~/.ssh/id_ed25519 (private) and .pub (public)
$ ssh-keygen -lf ~/.ssh/id_ed25519.pub          # its fingerprint
256 SHA256:r9kRUjoTTeZfWC6kJsG7Plwe22vjyNAvM35ng5fPaYo rajeev@laptop (ED25519)
$ ssh-copy-id deploy@10.0.1.15                  # adds your public key to the server's ~/.ssh/authorized_keys
$ ssh deploy@10.0.1.15
```

The **private key** stays on your machine, with permissions `600` (SSH refuses keys others can read).
The **public key** goes into `~/.ssh/authorized_keys` on each server. The first time you connect,
SSH shows the server's fingerprint and saves it in `~/.ssh/known_hosts`; if it ever changes, SSH
warns you loudly, because someone may be in the middle.

Save typing with `~/.ssh/config`:

```text
Host web1
    HostName 10.0.1.15
    User deploy
    IdentityFile ~/.ssh/id_ed25519

Host app-private
    HostName 10.0.2.20
    User deploy
    ProxyJump web1          # reach a private server through web1
```

Now `ssh web1` is enough, and `ssh app-private` hops through `web1` automatically.

> **In production: harden sshd.** In `/etc/ssh/sshd_config` set `PasswordAuthentication no` and `PermitRootLogin no`. Check the file with `sudo sshd -t`, then `sudo systemctl reload ssh` (`sshd` on RHEL). Keep your current session open and test a new login in a second terminal before you close it.

> **Video.** [Linux Crash Course - Public Key Authentication](https://www.youtube.com/watch?v=bfwfRCCFTVI&t=312s) (Learn Linux TV)

## Copying files: scp and rsync

Moving files to a remote server by copying them through chat or manually uploading them is slow and hard to
repeat. `scp` copies files over SSH; `rsync` also compares source and destination so it can send only the
changes. Both rely on SSH authentication and the account's filesystem permissions.

```sh
$ scp app.tar.gz web1:/tmp/                      # copy a file up
$ scp web1:/var/log/nginx/error.log .            # copy a file down
$ rsync -avn ./site/ web1:/srv/site/             # -n: dry run, shows what would be sent
$ rsync -av --delete ./site/ web1:/srv/site/     # make the server's folder match exactly
$ rsync -avz --progress backup/ web1:/backups/   # -z compress, show progress
```

`rsync` sends only what changed, resumes interrupted copies, and keeps permissions and times with
`-a`. Use it for anything bigger than a few files or anything you copy twice. The trailing slash
matters: `site/` copies what's inside, `site` creates `/srv/site/site`. With `--delete`, files on the
server that aren't in your folder are removed, so always run with `-n` first.

> **Video.** [Linux File Transfers Made Easy with rsync](https://www.youtube.com/watch?v=KG78O53u8rY) (Learn Linux TV)

## Mission: Check a server's network from end to end

Your app can't reach its API at api.example.com. Before blaming anyone, test every step: your address, the route, the name lookup, and the connection on port 443, and save the results to show the team.

- You need: Any Linux machine with network access
- You'll have: ~/net-check.txt

```sh
$ cat > ~/net-check.sh <<'EOF'
#!/bin/bash
host=${1:-example.com}
echo "== my addresses"; ip -br addr | grep -v '^lo'
echo "== default gateway"; ip route show default
ip=$(getent ahostsv4 "$host" | awk 'NR==1 {print $1}')
echo "== DNS lookup of $host"; echo "${ip:-FAILED: name does not resolve}"
[ -n "$ip" ] || exit 1
echo "== route to $ip"; ip route get "$ip"
echo "== HTTPS on port 443"; curl -sS -o /dev/null -m 5 -w "HTTP %{http_code} in %{time_total}s\n" "https://$host/" || echo "FAILED: no connection"
EOF
$ bash ~/net-check.sh example.com > ~/net-check.txt
$ cat ~/net-check.txt
== my addresses
eth0             UP             172.29.94.205/20 fe80::215:5dff:fe72:6be6/64
== default gateway
default via 172.29.80.1 dev eth0 proto kernel
== DNS lookup of example.com
172.66.147.243
== route to 172.66.147.243
172.66.147.243 via 172.29.80.1 dev eth0 src 172.29.94.205 uid 1000
    cache
== HTTPS on port 443
HTTP 200 in 0.229564s
```

The first step that fails is your answer: no address or gateway is the network config, no lookup is
DNS, and a lookup with no connection is a firewall or the remote service. The _Troubleshooting_
lesson goes deeper on that last case.

## Try it

- Run `ip -br addr` and `ip route`, and name your address, subnet and gateway.
- Ask which route a packet to 1.1.1.1 takes with `ip route get 1.1.1.1`.
- Look up a name the way programs do with `getent ahostsv4 example.com`.
- Make a key with `ssh-keygen -t ed25519` and read its fingerprint with `ssh-keygen -lf`.
- Work out how many addresses a /26 has, then check your answer in the table in this lesson.
- Sync a folder to another with `rsync -avn` first (dry run), then without `-n`.

## Quiz

1. How many usable host addresses does 10.0.1.0/24 give you?
   - 256
   - **254: the network address (.0) and broadcast (.255) are reserved** (answer)
   - 24
   Why: /24 leaves 8 bits for hosts: 2^8 = 256 addresses, minus 2. Clouds reserve more: AWS keeps 5 per subnet, so a /24 there has 251.

2. ping 1.1.1.1 works, but ping google.com says "Temporary failure in name resolution". What's broken?
   - The network cable
   - **DNS: the server can reach the internet but can't turn names into addresses** (answer)
   - The firewall blocks ICMP
   Why: Reaching an IP proves routing works. The failure is in name resolution: check /etc/resolv.conf, resolvectl status and the DNS server.

3. Which route does Linux use for a packet when several routes match?
   - The first one in the table
   - **The most specific one, the longest prefix; the default route (0.0.0.0/0) only when nothing else matches** (answer)
   - A random one
   Why: A /24 route beats a /16, which beats the default. ip route get <address> shows the one chosen.

4. What does PasswordAuthentication no in sshd_config do?
   - Disables SSH
   - **Allows only key-based logins, which stops password-guessing attacks** (answer)
   - Removes all passwords from the server
   Why: Bots try passwords on every public SSH server all day. With keys only, there's no password to guess. Test a key login in a second session before you reload sshd.

5. rsync -av src/ dest/ versus rsync -av src dest/: what's the difference?
   - None
   - **With the slash, the contents of src go into dest; without it, you get dest/src** (answer)
   - The slash makes it recursive
   Why: A trailing slash on the source means "what's inside". Run with -n (dry run) first when you're unsure, especially with --delete.

## Resources

- [ip(8) manual](https://manpages.ubuntu.com/manpages/noble/man8/ip.8.html) (Ubuntu manpages)
- [Netplan documentation](https://netplan.readthedocs.io/en/stable/) (Netplan)
- [sshd_config(5) manual](https://manpages.ubuntu.com/manpages/noble/man5/sshd_config.5.html) (Ubuntu manpages)
- [rsync(1) manual](https://manpages.ubuntu.com/manpages/noble/man1/rsync.1.html) (Ubuntu manpages)
- [resolvectl(1): query and inspect DNS](https://manpages.ubuntu.com/manpages/noble/man1/resolvectl.1.html) (Ubuntu manpages)
- [LPIC-1 objectives 109.1 to 109.4 and 110.3](https://wiki.lpi.org/wiki/LPIC-1_Objectives_V5.0) (Linux Professional Institute)
