Sub topic 16
Network address types
This chapter covers PostgreSQL's four network address types: inet, cidr, macaddr and macaddr8. It assumes you can create tables and run queries in psql. It also assumes you know what an IPv4 address, a subnet mask and CIDR notation such as 10.0.0.0/8 are. It builds on the casting chapter, because most mistakes with these types come from text-to-type conversion.
Why not store addresses as text
You can keep an IP address in a text column. The database will then accept 999.1.1.1 and hello, and it can't answer "is this address inside that network?" without string tricks. String order is also wrong: '10.0.0.9' > '10.0.0.10' is true as text.
The network types fix this:
- They reject malformed input at insert time.
- They sort in numeric address order.
- They provide operators for containment and overlap.
- They store IPv4 addresses compactly.
| Type | Holds | Storage | Typical use |
|---|---|---|---|
| `inet` | A host address, optionally with a netmask length | 7 bytes (IPv4) or 19 bytes (IPv6) | Client IPs, interface addresses |
| `cidr` | A network specification, with no host bits set | 7 or 19 bytes | Allow lists, routing prefixes |
| `macaddr` | A 6-byte hardware address | 6 bytes | Device identifiers |
| `macaddr8` | An 8-byte hardware address (EUI-64) | 8 bytes | Newer hardware, IPv6 interface IDs |
inet and cidr
Both types accept IPv4 and IPv6 in one column. inet stores any address, and it can carry a mask length. cidr stores a network, so it requires that every bit to the right of the mask is zero.
SELECT '192.168.1.5'::inet AS host_only,
'192.168.1.5/24'::inet AS host_with_mask,
'192.168.1.0/24'::cidr AS network,
'2001:db8::1'::inet AS ipv6_host;An inet value without a mask has an implicit length of 32 (IPv4) or 128 (IPv6). psql omits the implicit /32 when displaying it.
Putting host bits into a cidr value is an error:
SELECT '192.168.1.5/24'::cidr;
-- ERROR: invalid cidr value: "192.168.1.5/24"
-- DETAIL: Value has bits set to right of mask.Use cidr for column values that name a network. Use inet when the host part matters, for example when a row stores "this interface has address 192.168.1.5 on a /24 network".
Functions for taking addresses apart
SELECT host('192.168.1.5/24'::inet) AS host, -- 192.168.1.5
masklen('192.168.1.5/24'::inet) AS masklen, -- 24
network('192.168.1.5/24'::inet) AS network, -- 192.168.1.0/24
broadcast('192.168.1.5/24'::inet) AS broadcast, -- 192.168.1.255/24
netmask('192.168.1.5/24'::inet) AS netmask, -- 255.255.255.0
family('2001:db8::1'::inet) AS family; -- 6network() returns a cidr, so it is the usual way to turn a host address into its enclosing network. text() and host() differ: text() includes the mask length even when it is implicit, and host() never does.
Arithmetic works too. Adding an integer moves the address, and subtracting two addresses returns a bigint:
SELECT '192.168.1.10'::inet + 5 AS plus_five, -- 192.168.1.15
'192.168.1.43'::inet - '192.168.1.19'::inet AS distance; -- 24Containment operators
The operators that make these types worth using are the containment ones.
| Operator | Meaning |
|---|---|
| `a << b` | `a` is strictly inside network `b` |
| `a <<= b` | `a` is inside `b` or equal to it |
| `a >> b` | `a` strictly contains `b` |
| `a >>= b` | `a` contains or equals `b` |
| `a && b` | The two networks overlap |
"Strictly" matters. '10.0.0.0/8'::inet << '10.0.0.0/8'::inet is false, and <<= returns true. For a single host with no mask, the host is /32, so <<= against a network that contains it is the check you almost always want.
Worked example: matching clients to networks
CREATE TABLE allowed_networks (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
network cidr NOT NULL UNIQUE,
label text NOT NULL
);
CREATE TABLE access_log (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
client_ip inet NOT NULL,
device_mac macaddr,
seen_at timestamptz NOT NULL DEFAULT now()
);
INSERT INTO allowed_networks (network, label) VALUES
('10.0.0.0/8', 'Corporate'),
('10.1.0.0/16', 'Branch office'),
('192.168.0.0/16', 'Lab'),
('2001:db8::/32', 'Documentation IPv6');
INSERT INTO access_log (client_ip, device_mac) VALUES
('10.1.2.3', '08:00:2b:01:02:03'),
('192.168.1.5', '08-00-2b-01-02-04'),
('8.8.8.8', NULL),
('2001:db8::1', '0800.2b01.0205');
SELECT DISTINCT ON (l.id) l.client_ip, n.label
FROM access_log AS l
LEFT JOIN allowed_networks AS n ON l.client_ip <<= n.network
ORDER BY l.id, masklen(n.network) DESC;The address 10.1.2.3 matches both 10.0.0.0/8 and 10.1.0.0/16. Ordering by masklen(n.network) DESC and keeping the first row per client picks the most specific network. This is the longest-prefix match that routers use. The result is:
| client_ip | label |
|---|---|
| 10.1.2.3 | Branch office |
| 192.168.1.5 | Lab |
| 8.8.8.8 | (null) |
| 2001:db8::1 | Documentation IPv6 |
Indexing
A default B-tree index on an inet or cidr column supports equality and ordering (=, <, >, ORDER BY). It does not help containment operators. For those, create a GiST index with the inet_ops operator class, which you must name explicitly because it is not the default for GiST:
CREATE INDEX allowed_networks_network_idx
ON allowed_networks USING gist (network inet_ops);This index supports <<, <<=, >>, >>= and &&, along with the comparison operators. An SP-GiST index with inet_ops is another option. Test both on your own data if the table is large. A UNIQUE constraint, as on network above, creates a B-tree index automatically, which serves exact lookups only.
MAC addresses
macaddr accepts several common spellings and always prints the colon form:
SELECT '08:00:2b:01:02:03'::macaddr AS colon,
'08-00-2b-01-02-03'::macaddr AS dash,
'08002b:010203'::macaddr AS split,
'0800.2b01.0203'::macaddr AS dotted,
'08002b010203'::macaddr AS bare,
trunc('08:00:2b:01:02:03'::macaddr) AS vendor_prefix;
-- vendor_prefix: 08:00:2b:00:00:00trunc() zeroes the last three bytes, leaving the manufacturer prefix (the OUI). Use macaddr8 for 8-byte identifiers. Casting a 6-byte value to it inserts ff:fe in the middle, which is the standard EUI-48 to EUI-64 conversion:
SELECT '08:00:2b:01:02:03'::macaddr8; -- 08:00:2b:ff:fe:01:02:03Going back with ::macaddr works only for values that have ff:fe in those positions. Otherwise PostgreSQL raises an error.
Common errors and gotchas
- Host bits in a
cidrvalue. The error above usually appears when a/24is typed with a host address. Fix the data, or useinetand applynetwork()when you need the prefix. - Comparing with text.
WHERE client_ip = '10.1.2.3'works because the literal is coerced toinet. Comparing against atextcolumn or parameter fails with an operator error, so cast it:client_ip = $1::inet. - Mask length changes equality.
'10.1.2.3/24'::inetand'10.1.2.3'::inetare not equal. Compare withhost(a) = host(b)when you want to ignore the mask. - Mixed families. IPv4 and IPv6 can share a column. They never overlap, and every IPv4 value sorts before every IPv6 value.
- Abbreviated input.
'192.168.1'::cidris read as192.168.1.0/24. Avoid shortened forms in application data.
Exercise
A table has a column ip inet. Write a query that counts rows whose address is inside 172.16.0.0/12, and name the index type and operator class that lets PostgreSQL use an index for it.
Show answer
SELECT count(*) FROM hosts WHERE ip <<= '172.16.0.0/12'; An index created with CREATE INDEX ON hosts USING gist (ip inet_ops); supports the <<= operator. A default B-tree index would not.
Exercise
Why does INSERT INTO t (net) VALUES ('10.0.5.7/16') fail when net is cidr, and which two changes would make it succeed?
Show answer
The value has host bits set to the right of the /16 mask, so cidr rejects it. Either change the value to '10.0.0.0/16', or change the column type to inet (and use network(net) when you need the prefix).