# Fundamentals of internet protocols

> IPv4 addresses, masks and CIDR, private ranges, TCP, UDP and ICMP, the ports you must know, and what IPv6 changes.

Source: https://aminbytes.dev/bytes/networking-fundamentals/internet-protocols/


Every network problem you will ever debug comes back to a few basics: which address a machine has, which network it thinks it is on, and which protocol and port a service uses. If you can read `192.168.10.77/26` and instantly know the network, the broadcast and how many hosts fit, half the troubleshooting is done before you type a command.

This byte is the theory part of LPIC-1 topic 109. The next bytes put it to work with real configuration and tools. For what happens on top of these protocols (requests, headers, status codes), see the [HTTP topic](../../http/basics/what-is-http/).

## IPv4 addresses

An IPv4 address is 32 bits. People write it as four numbers from 0 to 255, separated by dots. This is called **dotted-quad** notation, and each number is an **octet** (8 bits):

```text
192      .168      .10       .77
11000000 .10101000 .00001010 .01001101
```

Every address has two parts. The **network part** says which network the machine is on. The **host part** says which machine on that network. The **netmask** decides where the line between them falls.

## Netmasks and CIDR notation

A netmask is also 32 bits: ones for the network part, zeros for the host part. You can write it in two ways:

- **Dotted-quad mask:** `255.255.255.0`
- **CIDR prefix:** `/24`, the number of one bits. CIDR stands for Classless Inter-Domain Routing.

So `192.168.10.77/24` and `192.168.10.77` with mask `255.255.255.0` mean the same thing. Linux tools such as `ip` use the CIDR form.

| Prefix | Netmask           | Addresses | Usable hosts |
| ------ | ----------------- | --------- | ------------ |
| `/8`   | `255.0.0.0`       | 16,777,216 | 16,777,214  |
| `/16`  | `255.255.0.0`     | 65,536    | 65,534       |
| `/20`  | `255.255.240.0`   | 4,096     | 4,094        |
| `/24`  | `255.255.255.0`   | 256       | 254          |
| `/25`  | `255.255.255.128` | 128       | 126          |
| `/26`  | `255.255.255.192` | 64        | 62           |
| `/27`  | `255.255.255.224` | 32        | 30           |
| `/28`  | `255.255.255.240` | 16        | 14           |
| `/30`  | `255.255.255.252` | 4         | 2            |
| `/32`  | `255.255.255.255` | 1         | a single host |

The rule: a `/n` network has 2<sup>(32 − n)</sup> addresses. Two of them are reserved, so you can give out 2<sup>(32 − n)</sup> − 2 to hosts:

- The **network address**: all host bits 0. It names the network itself.
- The **broadcast address**: all host bits 1. A packet sent there goes to every host on the network.

The values that show up in masks are always the same eight: `0, 128, 192, 224, 240, 248, 252, 254, 255`. Learn them and you can convert between mask and prefix in your head.

### Subnetting

**Subnetting** means borrowing host bits to split one network into smaller ones. Take `192.168.10.0/24` and split it into four networks. Four needs 2 extra bits, so each piece is a `/26` with 64 addresses:

| Subnet              | Network address | First host       | Last host         | Broadcast         |
| ------------------- | --------------- | ---------------- | ----------------- | ----------------- |
| `192.168.10.0/26`   | `.0`            | `.1`             | `.62`             | `.63`             |
| `192.168.10.64/26`  | `.64`           | `.65`            | `.126`            | `.127`            |
| `192.168.10.128/26` | `.128`          | `.129`           | `.190`            | `.191`            |
| `192.168.10.192/26` | `.192`          | `.193`           | `.254`            | `.255`            |

A quick way to find the network of any address: find the octet where the mask is not 255 or 0. Subtract that mask value from 256 to get the **block size**. The network starts at the largest multiple of the block size that fits.

Example: `172.16.45.130/20`. The mask is `255.255.240.0`. The interesting octet is the third one: 256 − 240 = 16, so networks start at 0, 16, 32, 48 and so on. 45 lies between 32 and 47, so the network is `172.16.32.0/20` and the broadcast is `172.16.47.255`.

You can check your math with `ipcalc` (`sudo apt install ipcalc` on Debian and Ubuntu). The `-b` option leaves out the binary columns:

```bash
ipcalc -b 192.168.10.77/26
```

```text
Address:   192.168.10.77
Netmask:   255.255.255.192 = 26
Wildcard:  0.0.0.63
=>
Network:   192.168.10.64/26
HostMin:   192.168.10.65
HostMax:   192.168.10.126
Broadcast: 192.168.10.127
Hosts/Net: 62                    Class C, Private Internet
```

> [!NOTE]
> Fedora and RHEL ship a different program also called `ipcalc`, with other options. There, `ipcalc -n -b 192.168.10.77/26` prints `NETWORK=192.168.10.64` and `BROADCAST=192.168.10.127`.

### The old address classes

Before CIDR (1993), the first octet fixed the mask. You still see the names, and `ipcalc` still prints them:

| Class | First octet | Default mask        |
| ----- | ----------- | ------------------- |
| A     | 1 to 126    | `255.0.0.0` (`/8`)  |
| B     | 128 to 191  | `255.255.0.0` (`/16`) |
| C     | 192 to 223  | `255.255.255.0` (`/24`) |
| D     | 224 to 239  | multicast           |
| E     | 240 to 255  | reserved            |

Today any prefix length can be used anywhere. "Class C" is just a casual way to say "a `/24`".

## Private and public addresses

**Public** addresses are unique on the whole internet. **Private** addresses, defined in RFC 1918, are free for anyone to use inside their own network, and routers on the internet never forward them:

| Range                           | CIDR             | Typical use              |
| ------------------------------- | ---------------- | ------------------------ |
| `10.0.0.0` to `10.255.255.255`     | `10.0.0.0/8`     | companies, cloud networks |
| `172.16.0.0` to `172.31.255.255`   | `172.16.0.0/12`  | Docker, VPNs             |
| `192.168.0.0` to `192.168.255.255` | `192.168.0.0/16` | home routers             |

Machines with private addresses reach the internet through **NAT** (Network Address Translation): the router swaps the private source address for its own public one on the way out, and back on the way in.

A few more special ranges you should recognize:

- `127.0.0.0/8`: **loopback**. `127.0.0.1` is always "this machine" and never leaves it.
- `169.254.0.0/16`: **link-local**. A machine gives itself one of these when it asked for DHCP and nobody answered. Seeing it usually means "DHCP failed".
- `0.0.0.0`: "any address" when a service listens, or "the default route" in a routing table.

 (Side note: Watch the `/12` trap: `172.16.0.0/12` covers 172.16 up to 172.31, so `172.20.1.1` is private but `172.32.1.1` is public.)

## TCP, UDP and ICMP

IP moves a packet from one address to another. Three protocols ride on top of it, and the exam wants you to know how they differ.

**TCP** (Transmission Control Protocol) is **connection-oriented**. Before any data flows, the two sides do a **three-way handshake**: `SYN`, `SYN-ACK`, `ACK`. Then TCP numbers every byte, acknowledges what arrived, resends what got lost, delivers everything in order and slows down when the network is congested. You pay for that with a bit of delay and overhead. SSH, HTTP, SMTP and IMAP use TCP.

**UDP** (User Datagram Protocol) is **connectionless**. It sends each datagram on its own: no handshake, no acknowledgments, no ordering, no resending. Its header is only 8 bytes, against at least 20 for TCP. That makes it fast and light, perfect for short questions and answers (DNS, NTP, SNMP, DHCP) and for live audio and video, where a late packet is worthless anyway.

**ICMP** (Internet Control Message Protocol) carries **control and error messages** for IP itself. It has no ports. It has message **types** instead:

| ICMP type | Meaning                  | Who uses it                |
| --------- | ------------------------ | -------------------------- |
| 8         | Echo request             | `ping` sends it            |
| 0         | Echo reply               | the answer to `ping`       |
| 3         | Destination unreachable  | "no route", "port closed"  |
| 11        | Time exceeded            | `traceroute` relies on it  |
| 5         | Redirect                 | "use another gateway"      |

| Feature            | TCP                 | UDP                   | ICMP                 |
| ------------------ | ------------------- | --------------------- | -------------------- |
| Connection         | yes (handshake)     | no                    | no                   |
| Reliable, ordered  | yes                 | no                    | no                   |
| Ports              | yes                 | yes                   | no (types and codes) |
| IP protocol number | 6                   | 17                    | 1 (ICMPv6: 58)       |
| Typical use        | SSH, HTTP, mail     | DNS, NTP, SNMP, syslog | ping, errors, traceroute |

The protocol numbers come from `/etc/protocols`, a small sister file of `/etc/services`.

> [!WARNING]
> Blocking all ICMP in a firewall looks safe but breaks things: path MTU discovery needs "too big" messages, and IPv6 cannot work at all without ICMPv6.

## Ports and /etc/services

A port is a 16-bit number (0 to 65535) that picks which program on a machine gets the data. TCP and UDP each have their own set: TCP port 53 and UDP port 53 are different doors.

- **0 to 1023**: well-known ports. Only root (or a program with the right capability) may listen on them.
- **1024 to 49151**: registered ports, for things like databases (MySQL is 3306).
- **49152 to 65535**: dynamic ports. Your side of an outgoing connection picks a temporary one. Linux uses 32768 to 60999 by default (see `/proc/sys/net/ipv4/ip_local_port_range`).

These are the ports the exam lists. Learn them by heart:

| Port | Protocol | Service |
| ---- | -------- | ------- |
| 20   | TCP | FTP data |
| 21   | TCP | FTP control (commands) |
| 22   | TCP | SSH, also `scp` and `sftp` |
| 23   | TCP | Telnet (unencrypted remote login) |
| 25   | TCP | SMTP (mail between servers) |
| 53   | UDP and TCP | DNS (TCP for big answers and zone transfers) |
| 80   | TCP | HTTP |
| 110  | TCP | POP3 (fetch mail) |
| 123  | UDP | NTP (time sync) |
| 139  | TCP | NetBIOS session service (old Windows file sharing, Samba) |
| 143  | TCP | IMAP (read mail on the server) |
| 161  | UDP | SNMP (monitoring queries) |
| 162  | UDP | SNMP traps (alerts sent by devices) |
| 389  | TCP | LDAP (directory) |
| 443  | TCP | HTTPS |
| 465  | TCP | SMTP over TLS (SMTPS, for mail clients) |
| 514  | UDP | syslog (remote logging); on TCP, the old `rsh` |
| 636  | TCP | LDAPS (LDAP over TLS) |
| 993  | TCP | IMAPS (IMAP over TLS) |
| 995  | TCP | POP3S (POP3 over TLS) |

A pattern helps: the TLS versions are 443 (HTTP), 465 (SMTP), 636 (LDAP), 993 (IMAP) and 995 (POP3).

Linux keeps this mapping in **`/etc/services`**. Each line is a name, a `port/protocol` and optional aliases:

```bash
grep -wE '^(ssh|domain|ntp|imaps)' /etc/services
```

```text
ssh             22/tcp                          # SSH Remote Login Protocol
domain          53/tcp                          # Domain Name Server
domain          53/udp
ntp             123/udp                         # Network Time Protocol
imaps           993/tcp                         # IMAP over SSL
```

Programs use this file to turn names into numbers and back. That's why `ss` shows `:ssh` instead of `:22` unless you add `-n`. You can also ask through the system's name service:

```bash
getent services 443/tcp
```

```text
https                 443/tcp
```

Changing `/etc/services` does **not** move a service to another port. It only changes the names tools print. The port a daemon listens on is set in that daemon's own configuration.

## IPv6

IPv4 has about 4.3 billion addresses, and they ran out years ago. NAT stretched them, but **IPv6** is the real fix.

### Writing IPv6 addresses

An IPv6 address is **128 bits**, written as eight groups of four hexadecimal digits separated by colons:

```text
2001:0db8:0000:0000:0000:ff00:0042:8329
```

Two rules make it shorter:

1. Drop **leading zeros** in each group: `0db8` becomes `db8`, `0042` becomes `42`.
2. Replace **one** run of all-zero groups with `::`. Only once, or nobody could tell how many zeros each `::` stands for.

```text
2001:db8::ff00:42:8329
```

The prefix works like CIDR in IPv4: `2001:db8:1:2::/64` means the first 64 bits are the network. A normal LAN subnet in IPv6 is always a `/64`, leaving 64 bits for hosts. In a URL, put the address in brackets so its colons don't clash with the port: `http://[2001:db8::1]:8080/`.

### Address types

| Address or prefix | Meaning |
| ----------------- | ------- |
| `::1`             | loopback (IPv4's `127.0.0.1`) |
| `::`              | unspecified, "any address" |
| `fe80::/10`       | **link-local**: every IPv6 interface has one, only valid on that link |
| `fc00::/7` (in practice `fd00::/8`) | **unique local**: the IPv6 version of private addresses |
| `2000::/3`        | **global unicast**: public internet addresses |
| `ff00::/8`        | **multicast**, for example `ff02::1` = all nodes on the link |
| `2001:db8::/32`   | reserved for documentation and examples |

Because every interface has a `fe80::` address, the same link-local address can exist on several interfaces. So you add the interface name after a `%`: `fe80::1%enp0s3`.

On a Linux machine you see both families side by side:

```bash
ip -br addr
```

```text
lo        UNKNOWN  127.0.0.1/8 ::1/128
enp0s3    UP       192.168.1.50/24 2001:db8:1:2:a00:27ff:fe4e:66a1/64 fe80::a00:27ff:fe4e:66a1/64
```

### What IPv6 changes

| Topic | IPv4 | IPv6 |
| ----- | ---- | ---- |
| Address size | 32 bits, dotted decimal | 128 bits, colon hexadecimal |
| Broadcast | yes | **none**, multicast is used instead |
| Finding neighbors | ARP | **NDP** (Neighbor Discovery Protocol) over ICMPv6 |
| Automatic addresses | DHCP | **SLAAC** (the host builds its own address from the router's prefix), or DHCPv6 |
| Header | variable, with a checksum | fixed 40 bytes, no checksum, extra "extension headers" |
| Fragmentation | sender and routers | **sender only**, routers send ICMPv6 "packet too big" |
| Minimum MTU | 68 bytes (every host must accept 576-byte packets) | 1280 bytes |
| NAT | common | not needed, every device can have a global address |
| IPsec | optional add-on | designed in from the start |

Most systems run **dual stack**: IPv4 and IPv6 at the same time, preferring IPv6 when both work. The `ping`, `traceroute` and `tracepath` commands have IPv6 versions (`ping6` and friends), covered in [basic network troubleshooting](../network-troubleshooting/).

 (Side note: SLAAC used to build the host part from the network card's MAC address (that's the `ff:fe` in the middle of `a00:27ff:fe4e:66a1`). Because that lets websites track a laptop across networks, modern systems also make random "privacy" addresses that change over time.)

## Exam checklist

- `/n` means n network bits. Hosts per network: 2<sup>(32 − n)</sup> − 2. Know masks `/8` to `/30` both as prefix and dotted quad.
- Network address = all host bits 0, broadcast = all host bits 1. Use the block size (256 minus the mask octet) to find them fast.
- Private ranges: `10.0.0.0/8`, `172.16.0.0/12`, `192.168.0.0/16`. Loopback `127.0.0.0/8`, link-local `169.254.0.0/16`.
- TCP: connection, handshake, reliable and ordered. UDP: connectionless, small header, no guarantees. ICMP: control messages, types instead of ports, used by `ping` and `traceroute`.
- Ports 20/21 FTP, 22 SSH, 23 Telnet, 25 SMTP, 53 DNS, 80 HTTP, 110 POP3, 123 NTP, 139 NetBIOS, 143 IMAP, 161/162 SNMP, 389 LDAP, 443 HTTPS, 465 SMTPS, 514 syslog, 636 LDAPS, 993 IMAPS, 995 POP3S.
- `/etc/services` maps service names to `port/protocol`. Editing it does not change where a daemon listens.
- IPv6: 128 bits, eight hex groups, drop leading zeros, `::` only once. `::1` loopback, `fe80::/10` link-local, `fc00::/7` unique local, `ff00::/8` multicast.
- IPv6 has no broadcast and no ARP (NDP instead), SLAAC for automatic addresses, a fixed 40-byte header, and only the sender fragments.


## Byte check

1. A host has the address `172.16.45.130/20`. What is its network address?
   - `172.16.45.0`
   - **`172.16.32.0`** (correct)
   - `172.16.0.0`
   A `/20` mask is `255.255.240.0`, so the third octet moves in blocks of 16. 45 falls in the block 32 to 47, so the network is `172.16.32.0`.

2. Which service normally listens on port `636`?
   - **LDAP over TLS (LDAPS)** (correct)
   - IMAP over TLS
   - SMTP over TLS
   Plain LDAP is 389 and LDAPS is 636. IMAPS is 993 and SMTP over implicit TLS is 465.

3. Which statement about IPv6 is true?
   - It uses broadcast to find neighbors, like ARP
   - Routers fragment packets that are too big, as in IPv4
   - **Addresses are 128 bits, and `::` may appear only once in an address** (correct)
   IPv6 has no broadcast (it uses multicast and Neighbor Discovery), and only the sender fragments. `::` can replace one run of zero groups, once.


