Skip to content

Instantly share code, notes, and snippets.

@dirkjanfaber
Created December 10, 2015 20:41
Show Gist options
  • Save dirkjanfaber/04a8c98cbf44be9bf295 to your computer and use it in GitHub Desktop.
Save dirkjanfaber/04a8c98cbf44be9bf295 to your computer and use it in GitHub Desktop.
Returns the in.arpa address for a given inet address. Check https://en.wikipedia.org/wiki/Reverse_DNS_lookup for more info.
create or replace function in_arpa(inet)
returns text
language plpgsql
as
$function$
declare
p_return text;
begin
case family($1)
when 4 then
select array_to_string(
array[a[4],a[3],a[2],a[1]], '.'
)||'.in-addr.arpa'
into p_return
from ( select string_to_array(
(split_part($1::text, '/', 1)), '.') as a ) as x;
when 6 then
select trim( leading '.' from
reverse(
regexp_replace(
array_to_string(
string_to_array(
host($1)
, ':'
, ''
) --string_to_array
, ''
, repeat('0', 32-length(replace(host($1), ':', '')))
) --array_to_string
, '', '.', 'g') --regexp_replace
) --reverse
) --trim
|| 'ip6.arpa'
into p_return;
end case;
return p_return;
end;
$function$;
comment on in_arpa( inet) is 'Returns the in.arpa address for a given inet address. Check https://en.wikipedia.org/wiki/Reverse_DNS_lookup for more info.';
@dirkjanfaber
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment