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.
The simplest is to use an existing web service for this.
There are plugins that let you do much more, including making your models geolocation-aware (geokit-rails) automatically, but if all you need is a country code for example, simply sending an HTTP Get to
http://api.hostip.info/country.php
(there are other services but this one does not require an API key) will return it, e.g. :Or polling http://api.hostip.info/ will return a full XML response with city, latitude, longitude, etc.
Be aware that the results you get are not 100% accurate. For example, right now I'm in France but reported as in Germany. This will be the case for pretty much any IP-based service.
You can try Yandex locator gem, service returns longitude, latitude and precision.
I've just published a gem for the IPLocate.io API which I created.
Super easy, no databases to download, and 1,500 free requests per day:
No Gem
It can also be used without a gem by just using Ruby's
Net::HTTP
andURI
:The request will return JSON so you can parse it and access it as follows:
You can use
geoip
gem.environment.rb
Download
GeoIP.dat.gz
fromhttp://www.maxmind.com/app/geolitecountry
. unzip the file. The below assumes under#{RAILS_ROOT}/db
dir.Here's a Ruby example calling the ipdata.co API.
It's fast and has reliable performance thanks to having 10 global endpoints each able to handle >10,000 requests per second!
Replace
78.8.53.5
with any ip you want to look upThat'd give you
One service you could use to do this is my own, https://ipinfo.io. It gives you country code and a bunch of other details:
If you just want the country you can get that by requesting
/country
You can then map from a country code to a name using the data from http://country.io, or using the example at http://ipinfo.io/developers/full-country-names