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

Database processing -- converting IP to geographic location with Python

編輯:Python

Use the database to IP Turn to specific geographical location

Realization principle

from This website Upload and download GeoLite2.mmdb, And then use geoip2 Process this database and correspond to IP Read information to get specific geographical location .

Code

import geoip2.database
reader = geoip2.database.Reader('downloads/GeoLite2.mmdb') # Database path 
def ip_print_AddrInfo(ip):
# Load data 
response = reader.city(ip)
# Country code 
Country_IsoCode = response.country.iso_code
# Country name 
Country_Name = response.country.name
# Chinese country name 
Country_NameCN = response.country.names['zh-CN']
# state / Province name 
Country_SpecificName = response.subdivisions.most_specific.name
# state / Save code 
Country_SpecificIsoCode = response.subdivisions.most_specific.iso_code
# The city name 
City_Name = response.city.name
# Postal Code 
City_PostalCode = response.postal.code
# latitude 
Location_Latitude = response.location.latitude
# longitude 
Location_Longitude = response.location.longitude
# Output 
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)

Functional expansion

IPv4 yes IP The fourth version of the agreement . It has a 32 byte , The format is a.b.c.d among a、b、c、d by 0-255 The integer of , Presumably 430 Billion possible permutations . But with the development of the Internet ,IPv4 Almost all domain names have been registered . thus ,IPv6 emerge as the times require , Provide a large number of empty domain names for website developers .

IP It can be used to locate the geographical location of a networked hardware . For example, enter Baidu website IPv4 Address , You can get the location of the server you are connected to . Some servers avoid DDOS Other attacks , Will use a proxy server to disguise the location of the primary server . therefore , The location may not be very accurate .

On the Internet, you can directly convert the website into IP Address tools , Guys, you can try This website . Bloggers will also upload it soon python A tutorial to realize this function , Stay tuned !


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