IP Address Geolocation With Python
Attempting to find the geographic location of an IP address can be quite frustrating with python on Linux. I had several issues attempting to get a library and database that were compatible with each other. Eventually I realized that the version of the database both openSUSE and Fedora ship were not compatible with the version of pygeoip that pip installs. To work around this, I had to manually download the GeoIP database from here and save it somewhere on the filesystem. Then I just told python the path to the database and everything seemed to work fine from there. Here is the script, feel free to use it as you wish:
Как определить местоположение по ip python
Geolocating an IP address is a convenient way to identify a user’s real-world location. This information can be used in a variety of ways to improve user experience, provide custom marketing, and restrict content by region. You can get a lot of data just from an IP address, like the user’s currency, timezone, whether they’re using a proxy or VPN, and general location. You can also use a timezone API to get more insight into specific data points.
With this information, you can improve user experience by tailoring your platform to the user. For example, you can display prices in the local currency, show dates and times in the appropriate regional format, and provide the location of the closest physical story. A common reason to do this geolocation is to show the European Users a cookie banner as required by GDPR and other regulations.
This blog post covers how to geolocate a user’s IP address using Python.
Don’t reinvent the wheel.
Abstract’s APIs are production-ready now.
Abstract’s suite of API’s are built to save you time. You don’t need to be an expert in email validation, IP geolocation, etc. Just focus on writing code that’s actually valuable for your app or business, and we’ll handle the rest.
Geolocate an IP address using an IP address database
One way to geolocate an IP address is to use an online geolocation database. One popular option, Geolocation DB, is free-to-use without an API key. This database includes a massive number of IP addresses obtained from Internet service providers. By querying the service, you can get an approximate location for a specified IP address.
For example, we can query Geolocation DB to geolocate the IP address 147.229.2.90 as follows:
For the provided IP address, this call returns the data:
Drawbacks to this approach
Because Geolocation DB is a free-to-use database, it does not provide much transparency toward the accuracy of its data. There also is not a method to easily confirm the validity of the IP locations. As a result, the use of this database introduces an unknown level of inaccuracy to geolocation data.
Additionally, this approach provides minimal information about the IP address and returns data exclusively referring to the estimated location. For example, accessing information like timezone and currency from this data would require querying secondary databases. This database also does not provide any information about whether the user is using a VPN to access the information. Since some people use VPNs to hide their real IP addresses and location, identifying the use of a VPN can be used to eliminate inaccurate location data.
Geolocate an IP address using Abstract’s geolocation API
Abstract API offers a free geolocation API that provides detailed information about user IP addresses. It provides information about the user’s location including city, state/region, country, and more, as well as information about their timezone, currency, and regional flag. The availability of this information makes it easy to customize your platform without querying external sources. Additionally, this API detects whether the user is connecting to the network via a VPN, making it easier to identify altered location data.
Python IP Geolocation
In this tutorial, we will be using geoip2 to find a geolocation of any IP Address.
geoip2 is a Python package provided by Maxmind. Two different products are offered with the geoip2 package. First is a web service. This is a pay per use product. You will need to sign up for a User ID and license key to use this. Second, there is a free version in which the database will be downloaded and stored locally. The free version is what we’ll be covering here.
For starters, we will need to install the package:
Once installed, we need to download the database from the Maxmind website:
Download and unzip using the terminal:
When unzipped, you will see a folder with a date appended to it (i.e. GeoLite2-City_20180206). Since this database is updated periodically, future downloads will have a different folder name. In this folder, the file we’re interested in is GeoLite2-City.mmdb, which is the database.
In order to read from this database, we’ll need to create a new Python file and import the geoip2 package.
Create the file:
Import the package:
Next, we will create a new reader variable and use that to open the database:
Next, given an IP address, we can get the IP geolocation info.
Now that we have the geolocation contained in the response variable, we can print the data we’re looking for:
Notice that “subdivisions” is what contains the state info.
Maxmind also follows the standards set by International Organization for Standardization (ISO), which is reflected in the iso_code properties. More info regarding country ISO codes can be found here.
Final note: other databases and a web service (mentioned earlier) are provided by Maxmind. The paid alternatives are generally more accurate and updated more frequently.
Возможно лт узнать местоположение человека в PYTHON?
в среде android (на телефонах и планшетах с этой ОС) для доступа к функциям системы используется специальная библиотека SL4A (Scripting Layer For Android) позволяющая из языка Python вызывать системные функции вроде показа уведомлений или доступа к GPS,Камере,Bluetooth.
в приложении QPython она уже интегрированна — запускается как сервис и обрабатывает вызовы из Python.
Как вы догадались состоит она из двух частей — кода на Python который мы подключаем «import android»
и кода на Java оформленного ввиде сервиса — друг без друга они не могут работать.
Таким образом можно получить координаты в программе на языке Python выполняемой на телефоне или планшете.
Name already in use
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Git stats
Files
Failed to load latest commit information.
README.md
AbstractAPI python-ip-geolocation library
Integrate the powerful IP Geolocation API from Abstract in your Python project in a few lines of code.
Abstract’s IP Geolocation API is a fast, lightweight, modern, and RESTful JSON API allowing you to look up the location, timezone, country details, and more of an IPv4 or IPv6 address.
It’s very simple to use: you only need to submit your API key and an IP address, and the API will respond with an assessment of its geographical location, as well as additional details like the timezone, if it’s a VPN address, and more.
Validating and verifying IP addresses is a critical step to reducing the chances of low-quality data and fraudulent or risky users in your website or application.
Supported Python Versions
This library supports the Python version 3.6 and higher.
You can install python-ip-geolocation via PyPi or by downloading the source.
python-ip-geolocation is available on PyPi as the abstract-python-ip-geolocation package:
Get your API key for free and without hassle from the Abstact website.
Geolocation from an IP Address
The API response is returned in a IpGeolocationData object.
PARAMETER | TYPE | DETAILS |
---|---|---|
Parameter | Type | Details |
ip_address | String | The requested IP address |
city | String | City’s name. |
city_geoname_id | String | City’s geoname ID. |
region | String | State or province in which the the city is located. |
region_iso_code | Char[2] | State or province’s ISO 3166-2 code. |
region_geoname_id | String | State or province’s geoname ID. |
postal_code | String | ZIP or postal code. |
country | String | Country’s name. |
country_code | Char[2] | Country’s ISO 3166-1 alpha-2 code. |
country_geoname_id | String | Country’s geoname ID. |
country_is_eu | Boolean | True if the country is in the EU, false if it is not. |
continent | String | Continent’s name. |
continent_code | Char[2] | 2 letter continent code: AF, AS, EU, NA, OC, SA, AN |
continent_geoname_id | String | Continent’s geoname ID. |
longitude | Float | Decimal of the longitude. |
latitude | Float | Decimal of the latitude. |
security > is_vpn | Boolean | Whether the IP address is using from a VPN or using a proxy |
timezone > name | String | Timezone’s name from the IANA Time Zone Database. |
timezone > abbreviation | String | Timezone’s abbreviation, also from the IANA Time Zone Database. |
timezone > gmt_offset | String | Timezone’s offset from Greenwich Mean Time (GMT). |
timezone > current_time | String | Current time in the local time zone. |
timezone > is_dst | Boolean | True if the location is currently in Daylight Savings Time (DST). |
flag > svg | String | Link to a hosted version of the country’s flag in SVG format. |
flag > png | String | Link to a hosted version of the country’s flag in PNG format. |
flag > emoji | String | Country’s flag as an emoji. |
flag > unicode | String | Country’s flag in unicode. |
currency > currency_name | String | The currency’s name. |
currency > currency_code | String | The currency’s code in ISO 4217 format. |
connection > connection_type | String | Type of network connection: Dialup, Cable/DSL, Cellular, Corporate |
connection > autonomous_system_number | Uint32 | Autonomous System number |
connection > autonomous_system_organization | String | Autonomous System Organization name. |
connection > isp_name | String | Internet Service Provider (ISP) name. |
connection > organization_name | String | Organization name. |
You will find additional information and request examples in the Abstract help page.
If you need help installing or using the library, please contact Abstract’s Support.
For bug report and feature suggestion, please use this repository issues page.
Contributions are always welcome, as they improve the quality of the libraries we provide to the community.
Please provide your changes covered by the appropriate unit tests, and post them in the pull requests page.
To install the requirements, run:
Once you implementer all your changes and the unit tests, run the following command to run the tests: