Skip to content

Instantly share code, notes, and snippets.

@Mon-Ouie
Forked from autarch/gist:3138158
Created July 18, 2012 19:20
Show Gist options
  • Save Mon-Ouie/3138234 to your computer and use it in GitHub Desktop.
Save Mon-Ouie/3138234 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'
# You could have used %w[country_code country_name], but I think symbols make
# more sense for such fields.
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 { |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
}.parse! # end.something looks odd
uri = URI::HTTP.build(:scheme => 'http',
:host => 'geoip.maxmind.com',
:path => '/e',
:query => URI.encode_www_form(:l => options[:license],
:i => options[:ip]))
# ^ I like aligning, though a parenthesis on its own line looked weird, and
# usually follow the 80-column rule.
response = Net::HTTP.get_response(uri)
unless response.is_a? Net::HTTPSuccess # if not => nuless
# also parenthesis vs no parenthesis is very arbitrary
abort "Request failed with status #{respones.code}"
# ^ abort = $stderr.puts + exit(1)
end
omni = Hash[fields.zip(response.body.encode('utf-8', 'iso-8859-1').parse_csv)]
if omni[:error]
abort "MaxMind returned an error code for the request: #{omni["error"]}"
else
puts # puts with no argument does what you want already
puts "MaxMind Omni data for #{options[:ip]}";
puts
omni.each { |key, val| printf " %-20s %s\n", key, val }
# tons of people have different rules about whitespaces for block
puts
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment