inet Operators Match Addresses To Subnets

Store IPv4 and IPv6 subnets in inet columns, then use containment and overlap operators to match addresses.

SqlSecurity Boundaries

Code

snippet
CREATE TABLE networks (
  id int PRIMARY KEY,
  label text NOT NULL,
  subnet inet NOT NULL
);

INSERT INTO networks (id, label, subnet)
VALUES
  (1, 'office', '10.0.0.0/8'),
  (2, 'lab', '192.168.1.0/24'),
  (3, 'vpn', '2001:db8::/32');

SELECT label,
       masklen(subnet) AS prefix_length,
       network(subnet) AS network_part,
       host(subnet) AS first_address
FROM networks
ORDER BY id;

SELECT '10.20.30.40'::inet << '10.0.0.0/8'::inet AS inside_office,
       '192.168.1.77'::inet <<= '192.168.1.0/24'::inet AS inside_or_equal,
       '192.168.1.0/24'::inet && '192.168.1.128/25'::inet AS overlaps;

SELECT '2001:db8::1'::inet <<= '2001:db8::/32'::inet AS inside_v6;

Inside the snippet

Several statements share this file — SELECT / INSERT / CREATE, with networks among the objects involved.

Mechanically, the statements are built from: an ORDER BY that fixes the output order; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity.

Using it

The networks table is the working surface here.

Key statements

SELECT '10.20.30.40'::inet << '10.0.0.0/8'::inet AS inside_office,
'192.168.1.77'::inet <<= '192.168.1.0/24'::inet AS inside_or_equal,
'192.168.1.0/24'::inet && '192.168.1.128/25'::inet AS overlaps;
SELECT label,
masklen(subnet) AS prefix_length,
network(subnet) AS network_part,
host(subnet) AS first_address
FROM networks
ORDER BY id;
INSERT INTO networks (id, label, subnet)
VALUES
(1, 'office', '10.0.0.0/8'),
(2, 'lab', '192.168.1.0/24'),
(3, 'vpn', '2001:db8::/32');

Interactive Tools for This Topic

FAQ

Which tables does the SQL touch?
`networks` — referenced directly, no join needed.