Skip to content

Instantly share code, notes, and snippets.

@autarch
Created July 18, 2012 19:11
Show Gist options
  • Save autarch/3138158 to your computer and use it in GitHub Desktop.
Save autarch/3138158 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
require 'csv'
require 'net/http'
require 'open-uri'
require 'optparse'
require 'uri'
fields = ['country_code',
'country_name',
'region_code',
'region_name',
'city_name',
'latitude',
'longitude',
'metro_code',
'area_code',
'time_zone',
'continent_code',
'postal_code',
'isp_name',
'organization_name',
'domain',
'as_number',
'netspeed',
'user_type',
'accuracy_radius',
'country_confidence',
'city_confidence',
'region_confidence',
'postal_confidence',
'error']
options = { :license => "YOUR_LICENSE_KEY", :ip => "24.24.24.24" }
OptionParser.new do |opts|
opts.banner = "Usage: omni-geoip-ws.rb [options]"
opts.on("-l", "--license LICENSE", "MaxMind license key") do |l|
options[:license] = l
end
opts.on("-i", "--ip IPADDRESS", "IP address to look up") do |i|
options[:ip] = i
end
end.parse!
uri = URI::HTTP.build(:scheme => 'http',
:host => 'geoip.maxmind.com',
:path => '/e',
:query => URI.encode_www_form(:l => options[:license], :i => options[:ip])
)
response = Net::HTTP.get_response(uri)
if ! response.is_a?(Net::HTTPSuccess)
$stderr.puts("Request failed with status #{response.code}")
exit(1)
end
omni = Hash[fields.zip(response.body.encode('utf-8', 'iso-8859-1').parse_csv)]
if omni["error"]
$stderr.puts("MaxMind returned an error code for the request: #{omni["error"]}")
exit(1)
else
puts ""
puts "MaxMind Omni data for #{options[:ip]}";
puts ""
omni.each {|key, val| printf " %-20s %s\n", key, val}
puts ""
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment