Skip to content

Instantly share code, notes, and snippets.

@nightfly19
Last active August 29, 2015 14:01
Show Gist options
  • Save nightfly19/c6c697c93bcf2bc00251 to your computer and use it in GitHub Desktop.
Save nightfly19/c6c697c93bcf2bc00251 to your computer and use it in GitHub Desktop.
subnet_hosts
create or replace function subnet_hosts(subnet cidr) returns setof inet as $$
declare
host inet := (inet (host(network(subnet))));
broadcast inet := (inet (host(broadcast(subnet))));
begin
if family(subnet) = 4 then
-- /32's are a special case
if masklen(subnet) = 32 then
return next subnet;
return;
exit;
end if;
-- The regular case
loop
host := host + 1;
if host = broadcast or not (host << subnet) then
return;
else
return next host;
end if;
end loop;
elsif family(subnet) = 6 then
-- /128's are a special case
if masklen(subnet) = 128 then
return next subnet;
return;
end if;
-- The regular case
loop
if not (host << subnet) then
return;
else
return next host;
end if;
host := host + 1;
end loop;
end if;
end
$$ language plpgsql
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment