Skip to content

Instantly share code, notes, and snippets.

@mbklein
Created November 5, 2019 16:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mbklein/71319addf2e03187dcf34fcdbf750c38 to your computer and use it in GitHub Desktop.
Save mbklein/71319addf2e03187dcf34fcdbf750c38 to your computer and use it in GitHub Desktop.
GeoIP database queries in Ruby
#!/usr/bin/env ruby
require 'csv'
require 'maxminddb'
db = MaxMindDB.new('./GeoLite2-City.mmdb')
CSV.open('results.csv', 'w') do |output|
output << ['IP', 'City', 'Subdivision', 'Country', 'Latitude', 'Longitude']
File.new('ips.txt','r').each_line do |line|
line.chomp!
result = db.lookup(line)
next if result.city.geoname_id.nil?
sub = ['CA','US'].include?(result.country.iso_code) ? result.subdivisions.most_specific.iso_code : result.subdivisions.most_specific.name
output << [line, result.city.name, sub, result.country.name, result.location.latitude, result.location.longitude]
$stderr.puts result.city.name
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment