Java - 通过IP地址获取用户所在地 (二)

2014-11-24 11:07:16 · 作者: · 浏览: 1
ense => "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!

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)

unless response.is_a (Net::HTTPSuccess)
abort "Request failed with status #{response.code}"
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 "MaxMind Omni data for #{options[:ip]}";
puts
omni.each { |key, val| printf " %-20s %s\n", key, val }
puts
end

#!/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 { |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!

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)

unless response.is_a (Net::HTTPSuccess)
abort "Request failed with status #{response.code}"
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 "MaxMind Omni data for #{options[:ip]}";
puts
omni.each { |key, val| printf " %-20s %s\n", key, val }
puts
end
最后再来个Perl版本吧:


[python]
#!/usr/bin/env perl

use strict;
use warnings;

use Encode qw( decode );
use Getopt::Long;
use LWP::UserAgent;
use Text::CSV_XS;
use URI;
use URI::QueryParam;

my @fields = qw(
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_r