LoginSignup
2
5

More than 5 years have passed since last update.

jupyter で、IPアドレスから、国、都市名を割り出す

Posted at

jupyter でちょっと便利なツールをつくっています。
今回は、IPアドレスから、国、都市名を割り出すスクリプトです。

geoip の設定

jupyter で使うことを念頭においています。
https://github.com/maxmind/geoip-api-python にしたがってインストール

IPアドレスと地域を結びつけるデータベースをダウンロードする必要あり

# データは、http://dev.maxmind.com/geoip/geoip2/geolite2/ にあります。無料のものです。(精度が高いのは有償です。)
# どの形式でどこにダウンロードするかですが、とりあえず、下記のようにします。
# mkdir /usr/local/share/GeoIP/
# cd /usr/local/share/GeoIP/
# wget http://geolite.maxmind.com/download/geoip/database/GeoLite2-Country.mmdb.gz
# gunzip GeoLite2-Country.mmdb.gz
# wget http://geolite.maxmind.com/download/geoip/database/GeoLite2-City.mmdb.gz
# gunzip GeoLite2-City.mmdb.gz

ここからがスクリプトのサンプル

import geoip2.database
# データベースの読み込み
reader = geoip2.database.Reader('/usr/local/share/GeoIP/GeoLite2-City.mmdb')
ip_addr = '202.232.86.11'
record = reader.city(ip_addr)
print(record.country.names['ja'])
print(record.city.names['ja'])
print(record.country.names['en'])
print(record.city.names['en'])

結果はこれです。

日本
東京
Japan
Tokyo

2
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
5