查詢IP地理位置或國家
阿新 • • 發佈:2018-12-23
分享如何從 IP 知道所屬城市或國家,這還滿神奇的,不需要連什麼web service,call 什麼 Restful API,直接透過資料庫離線或批次查詢mapping。
說明,透過下面的 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官方檔案:
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 使用方式:
anonymous_ip
(ip_address)- Get the AnonymousIP object for the IP address
Parameters: ip_address – IPv4 or IPv6 address as a string.
city
(ip_address)- Get the City object for the IP address
Parameters: ip_address – IPv4 or IPv6 address as a string.
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.
country
(ip_address)- Get the Country object for the IP address
Parameters: ip_address – IPv4 or IPv6 address as a string.
domain
(ip_address)- Get the Domain object for the IP address
Parameters: ip_address – IPv4 or IPv6 address as a string.
enterprise
(ip_address)- Get the Enterprise object for the IP address
Parameters: ip_address – IPv4 or IPv6 address as a string.
isp
(ip_address)- Get the ISP object for the IP address
Parameters: ip_address – IPv4 or IPv6 address as a string.
metadata
()- The metadata for the open database
Returns: maxminddb.reader.Metadata
object
資料庫似乎定期都會長大一點,請每個月回來重新下載 db 回去更新。
之前的技術類部落格文章都被google 刪光光了,其實沒什麼差,都是問了google 問題之後,copy & paste (複製/貼上)來的東西,被刪就算了。