Find IP address and location using python

Photo by henry perks on Unsplash

In this article, we shall see how to fetch the IP address of the user using python with the help of the built-in requests module.

What is the request module in python?

The requests module allows you to send HTTP requests like GET, POST, PUT and DELETE using Python. We are only going to use the get method to hit an url and get the response data

1. From “ipify.org”

The following url “https://api.ipify.org” returns the ip address of the user. This is how we execute the code in python.

But this url does not provide any additional information such as the address, state and country, etc of the user.

2. From “amazonaws.com”

Amazon AWS also provides us a way to fetch the IP address of the user using the url “https://checkip.amazonaws.com”. This will work even when connected to a VPN.

3. From “ipinfo.io”

This is the best site to get all data other than just our IP address. This site provides the following information.

  1. IP address
  2. city
  3. country
  4. region
  5. postal
  6. timezone

The following code snippet will show you how to get the above information from this site.

The above code when executed returns the following output.

ip: "161.185.160.93"
city: "New York City"
region: "New York"
country: "US"
postal: "10004"
timezone: "America/New_York"

They also have a python package but you may have to create an account to get the access keys. Hope this article was useful.

Happy coding!

Python Developer | Django Developer | Python Enthusiast