Skip to content

Instantly share code, notes, and snippets.

@begriffs
Last active February 23, 2016 05:56
Show Gist options
  • Select an option

  • Save begriffs/4d4736032920c5897d03 to your computer and use it in GitHub Desktop.

Select an option

Save begriffs/4d4736032920c5897d03 to your computer and use it in GitHub Desktop.
-- Find location of an IP address by reading ip2location_db5
-- (available from https://lite.ip2location.com/database-ip-country-region-city-latitude-longitude)
--
-- For instance the following returns San Francisco
-- select where_is('23.235.47.133');
CREATE OR REPLACE FUNCTION public.where_is(ip inet)
RETURNS SETOF ip2location_db5
LANGUAGE plpgsql
AS $function$
DECLARE
addr integer;
BEGIN
addr := $1 - '0.0.0.0'::inet;
RETURN QUERY SELECT * FROM ip2location_db5 WHERE ip_from <= addr AND ip_to >= addr;
END
$function$
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment