Skip to content

Instantly share code, notes, and snippets.

@stuartlynn
Created December 3, 2013 21:55
Show Gist options
  • Save stuartlynn/7778144 to your computer and use it in GitHub Desktop.
Save stuartlynn/7778144 to your computer and use it in GitHub Desktop.
Small Sinatra script for geocoding ips
require 'sinatra'
require 'pg'
require 'json'
require 'uri'
hash = URI.parse(ENV['HEROKU_POSTGRESQL_WHITE_URL'] || "http://localhost:5432/geo")
Client = PG.connect(hash.host, hash.port, nil , nil , hash.path.gsub("/",""), hash.user, hash.password)
# Client = Mysql2::Client.new(:host => "localhost", :username => "root")
def ip_convert(ip)
comps = ip.split(".").map(&:to_i)
(16777216 * comps[0]) + (65536 * comps[1]) + (256 * comps[2]) + comps[3]
end
def geocode(ip)
int_ip = ip_convert(ip)
Client.exec("SELECT l.country,l.region,l.city, l.latitude, l.longitude FROM location l JOIN blocks b ON (l.locId=b.locId) WHERE b.endIpNum >= #{int_ip} order by b.endIpNum limit 1;").first
end
get '/geocode/:ip' do
content_type 'application/javascript'
ips = params['ip'].split(",") || []
result = ips.collect{ |ip| {:ip=>ip, :result => geocode(ip)}}
result.to_json
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment