Sub topic 3
Writing and compressing addresses
This chapter assumes you know hexadecimal, binary, and IPv4 dotted-decimal notation. It also assumes you know that an IPv6 address has 128 bits, written as eight 16-bit groups.
The full form
A full IPv6 address has eight groups of four hexadecimal digits, separated by colons. Each group is 16 bits, so 8 × 16 = 128 bits. Hex digits are case-insensitive, but RFC 5952 recommends lowercase.
2001:0db8:0000:0000:0000:ff00:0042:8329This is hard to read and easy to mistype, so two compression rules exist.
Rule 1: drop leading zeros
In each group, you can remove leading zeros. A group that is all zeros becomes a single 0. You can't remove trailing zeros, because that changes the value: 0db8 becomes db8, but ff00 stays ff00.
2001:db8:0:0:0:ff00:42:8329Rule 2: replace one run of zero groups with ::
The double colon :: stands for one or more consecutive all-zero groups.
2001:db8::ff00:42:8329The :: can appear only once in an address. If it appeared twice, you couldn't tell how many zero groups each one replaced.
To expand a compressed address, count the groups that are written. Subtract that count from 8. The result is the number of zero groups that :: hides. In 2001:db8::ff00:42:8329, five groups are written, so :: stands for three zero groups.
Worked examples
| Full form | Compressed |
|---|---|
| `fe80:0000:0000:0000:0000:0000:0000:0001` | `fe80::1` |
| `2001:0db8:0000:0001:0000:0000:0000:0001` | `2001:db8:0:1::1` |
| `0000:0000:0000:0000:0000:0000:0000:0001` | `::1` |
| `0000:0000:0000:0000:0000:0000:0000:0000` | `::` |
In the second row there are two zero runs. The first is one group long and the second is three groups long. Only the longer run becomes ::.
Checking with Python
The ipaddress module converts between the two forms. It also rejects invalid text, such as an address with two ::.
import ipaddress
addr = ipaddress.ip_address("2001:0db8:0000:0000:0000:ff00:0042:8329")
print(addr.compressed) # 2001:db8::ff00:42:8329
print(addr.exploded) # 2001:0db8:0000:0000:0000:ff00:0042:8329Common mistakes
- Using
::twice, as in2001::db8::1. This is invalid. - Removing trailing zeros from a group, which changes the address.
- Miscounting hidden groups when expanding. Always check that the expanded address has exactly eight groups.
- Comparing addresses as plain text.
2001:DB8::1and2001:db8:0:0:0:0:0:1are the same address, so normalize them first.
Exercise
Expand 2001:db8:0:1::5 to its full form, then explain why 2001:db8::1::5 is invalid.
Show answer
Five groups are written (2001, db8, 0, 1, 5), so :: hides 8 − 5 = 3 zero groups. Padding each group to four digits gives 2001:0db8:0000:0001:0000:0000:0000:0005. The address 2001:db8::1::5 is invalid because :: appears twice, so the number of zero groups each one replaces can't be determined.