Определить страну по ip python

IP2Location 8.10.0

This is an IP geolocation library that enables the user to find the country, region, city, latitude and longitude, ZIP code, time zone, ISP, domain name, area code, weather info, mobile info, elevation, usage type, address type and IAB category from an IP address. It supports both IPv4 and IPv6 lookup.

Ссылки проекта

Статистика

Метаданные

Лицензия: MIT License

Сопровождающие

Классификаторы

Описание проекта

IP2Location 8.10.0

This is a IP2Location Python library that enables the user to find the country, region or state, city, latitude and longitude, ZIP code, time zone, Internet Service Provider (ISP) or company name, domain name, net speed, area code, weather station code, weather station name, mobile country code (MCC), mobile network code (MNC) and carrier brand, elevation, usage type, address type and IAB category by IP address or hostname originates from. The library reads the geo location information from IP2Location BIN data file.

Supported IPv4 and IPv6 address.

Requirements

Installation

  1. Unzip the package.
  2. Execute python setup.py build
  3. Execute python setup.py install

To install this module type the following (for PyPI):

Usage

You can check the sample.py file to learn more about usage.

BIN Database

Below is the description of the functions available in the BIN Database lookup.

Method Name Description
open Open the IP2Location BIN data for lookup. Default mode: File I/O.
close Close and clean up the file pointer.
get_all Returns the geolocation information in array.
get_country_short Returns the ISO3166-1 country code (2-digits) of the IP address.
get_country_long Returns the ISO3166-1 country name of the IP address.
get_region Returns the ISO3166-2 region name of the IP address. Please visit ISO3166-2 Subdivision Code for the information of ISO3166-2 supported
get_city Returns the city name of the IP address.
get_latitude Returns the city latitude of the IP address.
get_longitude Returns the city longtitude of the IP address.
get_isp Returns the ISP name of the IP address.
get_domain Returns the domain name of IP address.
get_zipcode Returns the zipcode of the city.
get_timezone Returns the UTC time zone (with DST supported).
get_netspeed Returns the Internet connection type. Please see Internet Connection Type for details.
get_idd_code Returns the IDD prefix to call the city from another country.
get_area_code Returns the area code of the city.
get_weather_code Returns the nearest weather observation station code.
get_weather_name Returns the nearest weather observation station name.
get_mcc Returns the Mobile Country Codes (MCC).
get_mnc Returns the Mobile Network Code (MNC).
get_mobile_brand Commercial brand associated with the mobile carrier. Please visit Mobile Carrier Coverage to view the coverage report.
get_elevation Returns average height of city above sea level in meters (m).
get_usage_type Returns the ISP’s usage type of IP address. Please see Usage Type for details.
get_address_type Returns the IP address type (A-Anycast, B-Broadcast, M-Multicast & U-Unicast) of IP address or domain name.
get_category Returns the IAB content taxonomy category of IP address or domain name. You can get a full list of IAB content taxonomy category from here.
get_district Returns the district or county name of IP address.
get_asn Returns the Autonomous system number (ASN) of IP address.
get_as Returns the Autonomous system (AS) name of IP address.
Читайте также:  Android java open database

Web Service

Below is the description of the functions available in the Web Service lookup.

  1. IP2Location API Key.
  2. Package (WS1 — WS25)
  3. Use HTTPS or HTTP
  • country_code
  • country_name
  • region_name
  • city_name
  • latitude
  • longitude
  • zip_code
  • time_zone
  • isp
  • domain
  • net_speed
  • idd_code
  • area_code
  • weather_station_code
  • weather_station_name
  • mcc
  • mnc
  • mobile_brand
  • elevation
  • usage_type
  • address_type
  • category
  • category_name
  • continent
    • name
    • code
    • hemisphere
    • translations
    • name
    • alpha3_code
    • numeric_code
    • demonym
    • flag
    • capital
    • total_area
    • population
    • currency
      • code
      • name
      • symbol
      • code
      • name
      • name
      • code
      • translations
      • name
      • translations
      • metro
      • olson
      • current_time
      • gmt_offset
      • is_dst
      • sunrise
      • sunset

      IP Tools

      Below is the description of the functions available in the IP Tools class.

      Function Name Description
      is_ipv4 Return either true or false. Verify if a string is a valid IPv4 address.
      is_ipv6 Return either true or false. Verify if a string is a valid IPv6 address.
      ipv4_to_decimal Translate IPv4 address from dotted-decimal address to decimal format.
      decimal_to_ipv4 Translate IPv4 address from decimal number to dotted-decimal address.
      ipv6_to_decimal Translate IPv6 address from hexadecimal address to decimal format.
      decimal_to_ipv6 Translate IPv6 address from decimal number into hexadecimal address.
      ipv4_to_cidr Convert IPv4 range into a list of IPv4 CIDR notation.
      cidr_to_ipv4 Convert IPv4 CIDR notation into a list of IPv4 addresses.
      ipv6_to_cidr Convert IPv6 range into a list of IPv6 CIDR notation.
      cidr_to_ipv6 Convert IPv6 CIDR notation into a list of IPv6 addresses.
      compressed_ipv6 Compress a IPv6 to shorten the length.
      expand_ipv6 Expand a shorten IPv6 to full length.

      Country Class

      Below is the description of the functions available in the Country class.

      • country_code
      • country_alpha3_code
      • country_numeric_code
      • capital
      • country_demonym
      • total_area
      • population
      • idd_code
      • currency_code
      • currency_name
      • currency_symbol
      • lang_code
      • lang_name
      • cctld

      Region Class

      Below is the description of the functions available in the Region class.

      Function Name Description
      Constructor Expect a IP2Location ISO 3166-2 Subdivision Code CSV file. This database is free for download at https://www.ip2location.com/free/iso3166-2
      get_region_code Provide a ISO 3166 country code and the region name to get ISO 3166-2 subdivision code for the region.

      Testing

      python sample.py python test.py python lookup.py

      Sample BIN Databases

      • Download free IP2Location LITE databases at https://lite.ip2location.com
      • Download IP2Location sample databases at https://www.ip2location.com/developers

      IPv4 BIN vs IPv6 BIN

      • Use the IPv4 BIN file if you just need to query IPv4 addresses.
      • Use the IPv6 BIN file if you need to query BOTH IPv4 and IPv6 addresses.

      Internet Connection Type

      Usage Type

      Usage Type Description
      COM Commercial
      ORG Organization
      GOV Government
      MIL Military
      EDU University/College/School
      LIB Library
      CDN Content Delivery Network
      ISP Fixed Line ISP
      MOB Mobile ISP
      DCH Data Center/Web Hosting/Transit
      SES Search Engine Spider
      RSV Reserved

      Источник

      Project_2. Местоположение с помощью IP-адреса (Python)

      Проект, который не отнимет много времени, но даст опыт, да и положительные эмоции.

      Описание

      С помощью скрипта и IP-адреса вычисляем местоположение. Определить точную геолокацию по IP-адресу невозможно: все сервисы, позволяющие находить информацию по IP, могут определить местоположение только на уровне города. Невозможно вычислить ваш или любой другой точный домашний адрес по IP. Это могут сделать правоохранительные органы только в том случае, если они обратятся к Интернет-провайдеру в случае нарушения вами закона.

      Код

      Создадим 2 файла, которые будут иметь разный функционал:

      Начнём с 1-го файла. Всё ещё импортируем то, что потребуется для реализации проекта.

      import requests import database

      Напоминаем, что database — это 2-й файл.

      Функция main() используется для разделения блоков кода в программе. Использование функции main() обязательно в таких языках, как Java, потому что это упрощает понимание того, в каком порядке код запускается в программе. В Python функцию main() писать необязательно, но это улучшает читаемость кода.

      Функция принимает в виде аргумента строку, которая просит ввести IP-адрес. Затем main() передаёт функции location() данные.

      def main(start: str): print(start) ip = input("IP address: ") try: new_data = location(ip) database.base(new_data) except ValueError: pass if __name__ == "__main__": main("Enter the IP address")

      Вторая функция location() принимает в виде аргумента строку с IP-адресом. Отправляем запрос с помощью метода get .

      GET является одним из самых популярных HTTP методов. Метод GET указывает на то, что происходит попытка извлечь данные из определенного ресурса. Для того, чтобы выполнить запрос GET , используется requests.get() .

      Используя .status_code , можно увидеть код состояния, который возвращается с сервера.

      Если будет выведено 404, то значит что-то пошло не так.

      Следующий этап — проверка на корректный IP-адрес. Если IP-адрес некорректный, то возвращает функцию main() с новой строкой, где сообщается, что нужно ввести корректный IP-адрес. Если всё хорошо, то создаём пустой список. С помощью цикла выводим все данные, которые необходимы и добавляем в список. Вывод будет выглядеть так.

      Enter the IP address IP address: 185.101.203.42 [Status]: success [Country]: Болгария [Countrycode]: BG [Region]: 22 [Regionname]: Sofia-Capital [City]: София [Zip]: 1000 [Lat]: 42.6951 [Lon]: 23.325 [Timezone]: Europe/Sofia [Isp]: SIA "Singularity Telecom" [Org]: SIA "Singularity Telecom" [As]: AS209372 SIA "Singularity Telecom" [Query]: 185.101.203.42

      Возвращаем кортеж с данными.

      def location(ip: str): response = requests.get(f"http://ip-api.com/json/?lang=ru") if response.status_code == 404: print("Oops") result = response.json() if result["status"] == "fail": return main("Enter the correct IP address") record = [] for key, value in result.items(): record.append(value) print(f"[]: ") return tuple(record)

      Теперь переходим ко второму файлу database.py , где будет создана база данных с добавлением новых данных.

      Импорт, как всегда, с нами. Для базы данных потребуется библиотека sqlite3 .

      Создаём функцию, которая принимает аргумент в виде кортежа.

      Во-первых, нам нужно создать новую базу данных и открыть подключение к базе данных, чтобы разрешить sqlite3 работать с ней. Вызов sqlite3.connect() поможет нам в том. Если базы данных database.db не существует, то будет неявно создана.

      Чтобы выполнять инструкции SQL и извлекать результаты из SQL-запросов, нам нужно будет использовать курсор базы данных. Вызов con.cursor() в деле.

      Теперь, когда у нас есть подключение к базе данных и курсор, мы можем создать таблицы базы данных со столбцами, которые необходимы.

      Если в базе данных уже присутствует какой-либо IP-адрес, то выводим «Duplicate «. Если нет, то добавляем в базу новые данные. Вызов conn.commit() зафиксирует транзакцию, скажем так. Так будет выглядеть база данных.

      Таблица

      def base(data: tuple): conn = sqlite3.connect("database.db") cur = conn.cursor() cur.execute("""CREATE TABLE IF NOT EXISTS location( Status TEXT, Country TEXT, Countrycode TEXT, Region TEXT, Regionname TEXT, City TEXT, Zip INT, Lat REAL, Lon REAL, Timezone TEXT, Isp TEXT, Org TEXT, Auto_system TEXT, Query TEXT); """) try: check = cur.execute(f"SELECT * FROM location WHERE Query=?", (data[-1],)) if len(list(*check)) == 0: cur.execute("INSERT INTO location VALUES(. );", data) conn.commit() else: print("Duplicate") except TypeError: pass

      Сценарий

      # Location by IP # Location search by IP address using Python import requests import database def location(ip: str): response = requests.get(f"http://ip-api.com/json/?lang=ru") if response.status_code == 404: print("Oops") result = response.json() if result["status"] == "fail": return main("Enter the correct IP address") record = [] for key, value in result.items(): record.append(value) print(f"[]: ") return tuple(record) def main(start: str): print(start) ip = input("IP address: ") try: new_data = location(ip) database.base(new_data) except ValueError: pass if __name__ == "__main__": main("Enter the IP address")
      import sqlite3 def base(data: tuple): conn = sqlite3.connect("database.db") cur = conn.cursor() cur.execute("""CREATE TABLE IF NOT EXISTS location( Status TEXT, Country TEXT, Countrycode TEXT, Region TEXT, Regionname TEXT, City TEXT, Zip INT, Lat REAL, Lon REAL, Timezone TEXT, Isp TEXT, Org TEXT, Auto_system TEXT, Query TEXT); """) try: check = cur.execute(f"SELECT * FROM location WHERE Query=?", (data[-1],)) if len(list(*check)) == 0: cur.execute("INSERT INTO location VALUES(. );", data) conn.commit() else: print("Duplicate") except TypeError: pass

      Заключение

      Некоторые компании специализируются на сборе информации о диапазоне IP-адресов со всего мира. Они продают эту информацию в виде консолидированных баз данных, которые легко интегрируются в любой веб-сервер с целью быстрого поиска информации о стране, регионе, городе или Интернет-провайдере. Точность этих баз данных колеблется от 80 до 99,8%, согласно их собственным утверждениям. Данный проект показал, как можно легко написать маленький скрипт, который будет собирать необходимую информацию с помощью таких баз.

      Источник

Оцените статью