牌語備忘録 -pygo

あくまでもメモです。なるべくオフィシャルの情報を参照してください。

牌語備忘録 -pygo

Pythonとipinfo.ioのapiでIPの地域を調べるメモ

ipinfo.io api

code

(python2.7.11)

$ pip install requests

# coding=utf8
import requests

def get_country(ips):
    result = []

    for ip in ips:
        response = requests.get('http://ipinfo.io/{}'.format(ip))
        country = response.json().get('country', '')
        region = response.json().get('region', '')

        if region:
            region = region.encode('utf-8')

        result.append([ip, country, region])

    return result


ips = [
    '157.55.39.101',
    '207.46.13.167',
    '68.180.228.95',
    '207.46.13.167',
    '157.55.39.101',
    '157.55.39.74',
    '68.180.228.95',
    '66.249.71.73',
]
unique_ips = list(set(ips))

print('{} (unique: {})'.format(
    len(ips),
    len(unique_ips),
))
print('\n'.join((['{},{},{}'.format(ip, country, result) for ip, country, result in get_country(unique_ips)])))

結果

8 (unique: 5)
207.46.13.167,US,Washington
68.180.228.95,US,California
157.55.39.74,US,Washington
157.55.39.101,US,Washington
66.249.71.73,US,California

リンク