Skip to content

Instantly share code, notes, and snippets.

@HemantNegi
Forked from rob-murray/select-next-ip.sql
Created September 26, 2019 05:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save HemantNegi/6c00dd1453559600031db30a951d441e to your computer and use it in GitHub Desktop.
Save HemantNegi/6c00dd1453559600031db30a951d441e 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