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

前端 未结 11 1629
一整个雨季
一整个雨季 2020-12-04 08:26

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

11条回答
  •  [愿得一人]
    2020-12-04 09:01

    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.

提交回复
热议问题