Reputation: 911
I know I can get user's IP address like this:
remote_ip = request.remote_ip
Now I was wondering how can I find out user's country and city from his IP address? I've found this buy it is only for country:
http://api.hostip.info/country.php
City can be found like this:
http://api.hostip.info
The problem is it is not showing the city correctly. I am currently in one of the biggest cities in the world and it says it is an unknown city.
What would be the best way to find out user's country and city from his IP address? I am looking for a free solution or at least something really cheap.
Thank you :)
Upvotes: 3
Views: 7065
Reputation: 570
One more solution is to use ruby gem for Yandex locator (https://tech.yandex.ru/locator/). Yandex locator is a service that finds mobile devices in a region delineated by a circle. The service returns longitude, latitude and precision. https://github.com/sergey-chechaev/yandex_locator
client = YandexLocator::Client.new(api_key: 'api key', version: '1.0')
result = client.lookup(ip: { address_v4: '178.247.233.3' })
result.position
# => {"altitude"=>0.0, "altitude_precision"=>30.0, "latitude"=>41.00892639160156, "longitude"=>28.96711158752441, "precision"=>100000.0, "type"=>"ip"}
Upvotes: 0
Reputation: 17541
You could try my API, https://ipinfo.io. It returns JSON by default, with a bunch of different fields:
$ curl ipinfo.io
{
"ip": "24.6.61.239",
"hostname": "c-24-6-61-239.hsd1.ca.comcast.net",
"city": "Mountain View",
"region": "California",
"country": "US",
"loc": "37.3845,-122.0881",
"org": "AS7922 Comcast Cable Communications, LLC",
"postal": "94040"
}
It's free for up to 1000 requests per day. See https://ipinfo.io/developers for more details.
Upvotes: 1
Reputation: 3448
You could try geocoder gem to obtain location by ip address:
Geocoder.search('5.18.186.107').first.city # => "Saint Petersburg"
Geocoder.search('213.180.204.26').first.country # => "Turkey"
Or even use built-in functionality w/o transitional actions:
# somewhere in your action
result = request.location # returns Geocoder::Result object
By default it uses http://freegeoip.net/ service for IP resolving, so in case you do not want to use any additional gems you can communicate with it using REST API.
Upvotes: 11
Reputation: 43
You can run a WHOIS with the IP address. I'm not sure if this can be done with code but if you want to do it only for a few IP's then sites like http://www.tools.whois.net/whoisbyip/ can provide information including city location. I believe different sites offer different depths of information.
Upvotes: 0