Skip to content

Instantly share code, notes, and snippets.

@rob-murray
Created January 8, 2013 17:31
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save rob-murray/4485873 to your computer and use it in GitHub Desktop.
Save rob-murray/4485873 to your computer and use it in GitHub Desktop.
Select the next available IP address using Postgres inet and cidr types
SELECT sub.ip FROM
(SELECT set_masklen(((generate_series(1,
(2 ^ (32 - masklen('10.10.100.0/24'::cidr)))::integer - 2) +
'10.10.100.0/24'::cidr)::inet), 32) as ip) AS sub
WHERE sub.ip NOT IN
(SELECT ip_address from ip_table)
AND sub.ip > set_masklen('10.10.100.0/24', 32)+10
AND sub.ip < set_masklen(broadcast('10.10.100.0/24')::inet, 32)-5;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment