查詢IP地理位置或國家

Posted in :

分享如何從 IP 知道所屬城市或國家,這還滿神奇的,不需要連什麼web service,call 什麼 Restful API,直接透過資料庫離線或批次查詢mapping。

Screenshot 2016-05-27 11.14.56

說明,透過下面的 source code, 第1次取得地區為 US, 第2次測試結果為 TW.

source code:

import geoip2.database
reader = geoip2.database.Reader(‘./GeoLite2-Country.mmdb’)
response = reader.country(‘218.161.70.131’)
print response.country.iso_code

測試 ip: 218.161.70.131 結果顯示 TW.

測試 ip: 128.101.101.101 結果顯示 US.

geoip2 的python官方文件:

https://pypi.python.org/pypi/geoip2

geoip2 安裝方式:

To install the geoip2 module, type:

$ pip install geoip2

If you are not able to use pip, you may also use easy_install from the source directory:

$ easy_install .

geoip2 使用方式:

https://geoip2.readthedocs.io/en/latest/

anonymous_ip(ip_address)
Get the AnonymousIP object for the IP address

Parameters: ip_address – IPv4 or IPv6 address as a string.
Returns: geoip2.models.AnonymousIP object
city(ip_address)
Get the City object for the IP address

Parameters: ip_address – IPv4 or IPv6 address as a string.
Returns: geoip2.models.City object
close()
Closes the GeoIP2 database
connection_type(ip_address)
Get the ConnectionType object for the IP address

Parameters: ip_address – IPv4 or IPv6 address as a string.
Returns: geoip2.models.ConnectionType object
country(ip_address)
Get the Country object for the IP address

Parameters: ip_address – IPv4 or IPv6 address as a string.
Returns: geoip2.models.Country object
domain(ip_address)
Get the Domain object for the IP address

Parameters: ip_address – IPv4 or IPv6 address as a string.
Returns: geoip2.models.Domain object
enterprise(ip_address)
Get the Enterprise object for the IP address

Parameters: ip_address – IPv4 or IPv6 address as a string.
Returns: geoip2.models.Enterprise object
isp(ip_address)
Get the ISP object for the IP address

Parameters: ip_address – IPv4 or IPv6 address as a string.
Returns: geoip2.models.ISP object
metadata()
The metadata for the open database

Returns: maxminddb.reader.Metadata object

geoip2 資料庫下載:http://dev.maxmind.com/geoip/geoip2/geolite2/

資料庫似乎定期都會長大一點,請每個月回來重新下載 db 回去更新。

之前的技術類部落格文章都被google 刪光光了,其實沒什麼差,都是問了google 問題之後,copy & paste (複製/貼上)來的東西,被刪就算了。

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *