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 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. :
Net::HTTP.get_response(URI.parse('http://api.hostip.info/country.php'))
=> US
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.