I am going to read you some addresses. Compress each one properly and tell me which ones are invalid.
Show the answer
Say this first
I apply the rules in order: strip leading zeros in each hextet, then put :: on the longest run of two or
more zero hextets, leftmost on a tie, and never on a single zero. An address is invalid if it has two ::,
more than eight hextets, a hextet over four hex digits, or a non-hex character.
Go deeper
Compress these
| Written out | Canonical | Why |
|---|---|---|
2001:0db8:0000:0000:0000:0000:0000:0001 | 2001:db8::1 | one long run |
2001:0db8:0000:0001:0000:0000:0000:0001 | 2001:db8:0:1::1 | the run of three wins over the single zero |
2001:0db8:0000:0000:0001:0000:0000:0001 | 2001:db8::1:0:0:1 | two runs of two, the leftmost wins |
2001:0db8:0000:0000:0001:0000:0000:0000 | 2001:db8:0:0:1:: | the run of three at the end beats the run of two |
2001:0db8:00a0:0000:0b00:0000:0000:0c00 | 2001:db8:a0:0:b00::c00 | only leading zeros go, 0b00 keeps its zeros |
2001:0db8:0000:0001:0001:0001:0001:0001 | 2001:db8:0:1:1:1:1:1 | a single zero hextet never gets :: |
FE80:0000:0000:0000:0202:B3FF:FE1E:8329 | fe80::202:b3ff:fe1e:8329 | lowercase, 0202 to 202 |
0:0:0:0:0:0:0:1 | ::1 | loopback |
0:0:0:0:0:0:0:0 | :: | unspecified |
Spot the invalid ones
| Address | Problem |
|---|---|
2001:db8::5::1 | two :: |
2001:db8:1:2:3:4:5:6:7 | nine hextets |
2001:db8:10000::1 | 10000 is 17 bits |
2001:db8:acad:1g::1 | g is not hex |
2001:db8:1:2:3:4:5::6 | eight hextets written plus ::, which must stand for at least one more |
How I check out loud
"I count the hextets. If :: is there, it fills the gap up to eight. Then I check each group is at most four
hex digits." Saying the method shows the interviewer you are not guessing.
They will ask next
Expand 2001:db8:0:a::b:0 to the full form.
Six hextets are written, so
::is two zero groups:2001:0db8:0000:000a:0000:0000:000b:0000.How would you check this quickly on a laptop?
python3 -c "import ipaddress; print(ipaddress.ip_address('2001:0db8::0001:0000'))"prints the canonical form and raises an error for an invalid one.ipaddress.ip_address(...).explodedgives the full form.
Traps
- Putting
::on the first zero run even when a later run is longer. - Calling
2001:db8:0:1:1:1:1:1wrong. It is valid and already canonical.