程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

數據庫處理——用Python將IP轉換為地理位置

編輯:Python

利用數據庫將IP轉為具體地理位置

實現原理

從這個網站上下載GeoLite2.mmdb,然後用geoip2處理這個數據庫並對應IP讀取信息來獲取具體地理位置。

代碼

import geoip2.database
reader = geoip2.database.Reader('downloads/GeoLite2.mmdb') #數據庫的路徑
def ip_print_AddrInfo(ip):
#載入數據
response = reader.city(ip)
#國家代碼
Country_IsoCode = response.country.iso_code
#國家名稱
Country_Name = response.country.name
#中文國家名稱
Country_NameCN = response.country.names['zh-CN']
#州/省名稱
Country_SpecificName = response.subdivisions.most_specific.name
#州/省代碼
Country_SpecificIsoCode = response.subdivisions.most_specific.iso_code
#城市名稱
City_Name = response.city.name
#郵政編碼
City_PostalCode = response.postal.code
#緯度
Location_Latitude = response.location.latitude
#經度
Location_Longitude = response.location.longitude
#輸出
print('Target: ' + ip + ' GeoLite2-Located ')
print(' Country_IsoCode : ' + Country_IsoCode)
print(' Country_Name : ' + Country_Name)
print(' Country _NameCN : ' + Country_NameCN)
print(' Country_SpecificName : ' + Country_SpecificName)
print(' Country_SpecificIsoCode: ' + Country_SpecificIsoCode)
print(' City_Name : ' + City_Name)
if City_PostalCode != None:
print(' City_PostalCode : ' + City_PostalCode)
print(' Location_Latitude : ' + str(Location_Latitude))
print(' Location_Longitude : ' + str(Location_Longitude))
ip = input("IPv4 address:")
ip_print_AddrInfo(ip)

功能拓展

IPv4是IP協議的第四版本。它擁有32字節,格式為a.b.c.d其中a、b、c、d為0-255的整數,有大概430億個可能的排列組合。但隨著互聯網的發展,IPv4的域名幾乎已經都被注冊了。由此,IPv6應運而生,給網站開發者提供了大量的空域名。

IP可以用來定位一個聯網硬件的地理位置。比如輸入百度網址的IPv4地址,就能得到你所連接的服務器的所在位置。有些服務器為了避免DDOS等其它攻擊,會用代理服務器來偽裝主服務器的位置。因此,定位的地理位置可能不是非常准確。

網上有直接把網址轉化成IP地址的工具,小伙伴們可以試試這個網站 。博主也會在不久後上傳用python實現這個功能的教程,敬請關注!


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved