Get Geolocation info of IP Address in Bash in Linux

Sometimes you need to get the geolocation information for an IP address quickly. In Linux, you can use the power of console apps to save your time and retrieve this information quickly. Let's see how it can be done.

To obtain the geo location information about a specific IP address, you need to use some online service which provides the appropriate API. It is a good idea to use some public service to avoid the authorization procedure and the API key management. One such service is FreeGeoIP.net.

It provides a public HTTP API to search the geolocation of IP addresses. It uses a database of IP addresses that are associated with cities along with other relevant information like time zone, latitude and longitude. This is very useful.

The service can provide search results as JSON or XML. So, if we combine curl with some JSON parser, we can get the required info.

I will use my favorite JSON parser, jq:

It is very lightweight and fast.

For our case, the query should be as follows:

http://freegeoip.net/json/119.94.116.145

The "json" portion here is the desired data format. Besides JSON, it can be XML or CSV.

Let's run the query with curl and see the output:

The result is raw JSON output which is hard to read. To improve the appearance of the result set, let's use the jq tool. Combine it with curl as follows:

curl http://freegeoip.net/json/119.94.116.145|jq

The output will be easier to read:

Using jq, you can filter the output and make it show only the required fields. The following command will display only the country name, latitude and longitude:

curl http://freegeoip.net/json/119.94.116.145|jq -r '.country_name,.latitude,.longitude'

You can save this command as the following shell script:

#!/bin/sh
curl -s http://freegeoip.net/json/$1|jq -r '.country_name,.latitude,.longitude'

The next time you need to get geolocation information, you can execute your script like this:

./geo.sh IP_address

That's it.

Support us

Winaero greatly relies on your support. You can help the site keep bringing you interesting and useful content and software by using these options:

If you like this article, please share it using the buttons below. It won't take a lot from you, but it will help us grow. Thanks for your support!

Author: Sergey Tkachenko

Sergey Tkachenko is a software developer who started Winaero back in 2011. On this blog, Sergey is writing about everything connected to Microsoft, Windows and popular software. Follow him on Telegram, Twitter, and YouTube.

2 thoughts on “Get Geolocation info of IP Address in Bash in Linux”

Leave a Reply

Your email address will not be published.

Exit mobile version
Using Telegram? Subscribe to the blog channel!
Hello. Add your message here.