Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting a user country name from originating IP address with Ruby on Rails

I want to extract a user country name from visitors' IP addresses.

I could get the IP address with remote_ip. But what could be the easiest way to get the country name?

It doesn't have to be super accurate. Any ruby library (gem or plugin) to do this?

I want an simple and easy solution for this.

like image 715
TK. Avatar asked Jan 01 '10 06:01

TK.


People also ask

Can you determine the country of origin from IP address?

Imp You can't get the country "just by looking at an IP address". Our service, IPinfo.io, infers the geographic location of IPs by pulling in many different data sources, and performing active scans across all IP addresses, and then publishes the results daily.

How can I tell what country an IP address belongs to?

You may also use 3rd party websites such as Geobytes or Dnsstuff to lookup the IP address. The whois lookup will reveal name of the ISP who owns that IP address, and the country where it is originated from. If you're lucky, you might also find the city of orgin.


1 Answers

You can use geoip gem.

environment.rb

config.gem 'geoip' 

Download GeoIP.dat.gz from http://www.maxmind.com/app/geolitecountry. unzip the file. The below assumes under #{RAILS_ROOT}/db dir.

@geoip ||= GeoIP.new("#{RAILS_ROOT}/db/GeoIP.dat")     remote_ip = request.remote_ip  if remote_ip != "127.0.0.1" #todo: check for other local addresses or set default value   location_location = @geoip.country(remote_ip)   if location_location != nil          @model.country = location_location[2]   end end 
like image 163
Chandra Patni Avatar answered Sep 20 '22 07:09

Chandra Patni