Finding geolocation from an IP address

geolocationiprubyshell-script

How can I find a location such as city/state or country from an IP address?

Is there a Ruby gem or Python module to do this? Or, is there a website which has an API?

Best Answer

You could use the http://ipinfo.io API for this:

$ curl ipinfo.io/8.8.8.8
{
  "ip": "8.8.8.8",
  "hostname": "google-public-dns-a.google.com",
  "city": "Mountain View",
  "region": "California",
  "country": "US",
  "loc": "37.3860,-122.0838",
  "org": "AS15169 Google Inc.",
  "postal": "94040"
}

If you're only interested in one field you can add that to the URL to get it as plain text:

$ curl ipinfo.io/8.8.8.8/loc
37.3860,-122.0838

$ curl ipinfo.io/8.8.8.8/country
US

If you're looking for a python module https://github.com/juanpabloaj/pyipinfo is a simple wrapper, or http://geocoder.readthedocs.org/en/stable/ is more fully featured and has built in support for ipinfo.io and other providers.

Related Question