Now that everyone is using IPv6 it might be time to start playing with it. Postgres has had full IPv6 support for years, so Postgres is a good place to start, particularly with IPv6-aware data types.
Since IPv6 addresses are 128-bits instead of IPv4's 32-bits, they can be quite long, e.g. 2001:0db8:85a3:0000:0000:8a2e:0000:7334. As you can see, it is made up of eight quad-hex segments, separated by colons. To shorten the text representation, leading zeros in any quad-hex segment can be removed, though an all-zero quad still requires a zero. In addition, the longest string of all-zero quads can be abbreviated with double colons. This can be illustrated in Postgres:
SELECT '2001:0db8:85a3:0000:0000:8a2e:0000:7334'::inet;
inet
------------------------------
2001:db8:85a3::8a2e:0:7334
In the output, 0db8 became db8, and :0000:0000: became ::, and the final 0000 became 0. An address with many leading zeros, e.g. localhost (0000:0000:0000:0000:0000:0000:0000:0001), gets dramatically shortened using these rules:
SELECT '0000:0000:0000:0000:0000:0000:0000:0001'::inet;
inet
------
::1
This highlights perhaps the most confusing aspect of IPv6 addresses — you can't just visually compare two IPv6 addresses to check for equality, like you can for IPv4. You must use the IPv6 rules for comparisons.
Use of colons is strictly for IPv6 addresses, i.e., 1::127 represents a 128-bit IPv6 value, not a 32-bit IPv4 one, as illustrated by the IP family() function:
SELECT family('1::127');
family
--------
6
SELECT family('1.0.0.127');
family
--------
4
SELECT '1::127'::inet = '1.0.0.127'::inet;
?column?
----------
f
Postgres is a fun, interactive way to play with the IPv6 address rules, because we are all going to have to learn them eventually.
Bruce Momjian is a Senior Database Architect at EnterpriseDB.
This post originally appeared on Bruce's personal blog.