sonickun.log

備忘録

GeoIPでIPアドレスから位置情報を取得する[Python]

 Pythonの「GeoIP」というモジュールを使ってIPアドレスドメイン名から国名などの位置情報を取得します.
 GeoIP 1.3.2 : Python Package Index
 

GeoIPのインストール

 インストール方法が少しややこしかったのでまとめておきます.

 事前にインストールが必要だったパッケージ(sudo apt-get installでインストール)

  • python-dev
  • libevent-dev
  • libgeoip-dev


 上のサイトから「GeoIP-1.3.1.tar.gz」をダウンロードして以下のコマンドを実行

$ tar xvzf GeoIP-1.3.1.tar.gz
$ cd GeoIP-1.3.1
$ python setup.py build
$ python setup.py install

 これでGeoIPモジュールが使えるようになります./GeoIP-1.3.1/example/以下にサンプルコードがあります.

 さらに,IPアドレスをマッチングするためのデータベースをダウンロードしてくる必要があります.
 GeoIP Country Database Installation Instructions « Maxmind Developer Site

 今回はGeoIP.datという国名に関するデータベースをダウンロードしましたが.都市の名前や組織の名前を取得できるデータベースもあるようです.以下コマンド

$ wget -N http://geolite.maxmind.com/download/geoip/database/GeoLiteCountry/GeoIP.dat.gz
$ gunzip GeoIP.dat.gz
$ mv GeoIP.dat /usr/local/share/GeoIP/

 データベースは「/usr/local/share/GeoIP/」以下に保存しました.
 
 

Python Scrypt

#!/usr/bin/python

from __future__ import print_function

import GeoIP

#インスタンスを定義(使用するデータベース指定する)
#gi = GeoIP.new(GeoIP.GEOIP_STANDARD)
#gi = GeoIP.new(GeoIP.GEOIP_MMAP_CACHE)
gi = GeoIP.new(GeoIP.GEOIP_MEMORY_CACHE)
#gi = GeoIP.open("/usr/local/share/GeoIP/GeoIP.dat",GeoIP.GEOIP_STANDARD)

print(gi.country_code_by_name("yahoo.com"))          # ドメイン名から2文字のCountry Codeを取得
print(gi.last_netmask())                             # その国のネットマスクを取得
print(gi.country_name_by_name("www.bundestag.de"))   # ドメイン名から国名を取得
print(gi.country_code_by_addr("24.24.24.24"))        # IPアドレスから2文字のCountry Codeを取得
print(gi.country_name_by_addr("24.24.24.24"))        # IPアドレスから国名を取得
print(gi.range_by_ip("68.180.206.184"))              # その国のIPレンジを取得

Results

US
17
Germany
US
United States
('68.179.128.0', '68.181.255.255')