Created
December 3, 2013 21:55
-
-
Save stuartlynn/7778144 to your computer and use it in GitHub Desktop.
Small Sinatra script for geocoding ips
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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