前言:
当前咱们对“python如何查看地址”大概比较关心,看官们都想要分析一些“python如何查看地址”的相关文章。那么小编也在网络上汇集了一些有关“python如何查看地址””的相关资讯,希望咱们能喜欢,看官们一起来学习一下吧!1.导入必要的库
import socketimport requestsfrom ip2geotools.databases.noncommercial import DbIpCityfrom geopy.distance import distance
以下函数用于打印 IP 地址行城市、国家、坐标等详细信息。
def printDetails(ip): res = DbIpCity.get(ip, api_key="free") print(f"IP Address: {res.ip_address}") print(f"Location: {res.city}, {res.region}, {res.country}") print(f"Coordinates: (Lat: {res.latitude}, Lng: {res.longitude})")2. 从 IP 地址获取位置
ip_add = input("Enter IP: ") # 198.35.26.96printDetails(ip_add)
输出:
IP Address: 198.35.26.96Location: San Jose, California, USCoordinates: (Lat: 37.3361663, Lng: -121.890591)3. 从 URL 获取位置
url = input("Enter URL: ") # = socket.gethostbyname(url)printDetails(ip_add)
输出:
Enter the URL: Address: 173.194.214.91Location: Mountain View, California, USCoordinates: (Lat: 37.3893889, Lng: -122.0832101)常见的用例1. 根据位置阻止某些 IP 地址
下面的代码查找 IP 地址的位置,然后检查该位置所在的国家/地区是否在被阻止的国家/地区列表中。
def is_country_blocked(ip_address): blocked_countries = ["China", "Canada", "India"] location = DbIpCity.get(ip_address) if location.country in blocked_countries: return True else: return Falseip_add = input("Enter IP: ") # 198.35.26.96if is_country_blocked(ip_add) is True: print(f"IP Address: {ip_add} is blocked")else: print(f"IP Address: {ip_add} is allowed")
输出:
Enter the IP Address: 198.35.26.96IP Address: 198.35.26.96 is allowed2. 计算两个IP地址之间的距离
下面的代码将计算两个 IP 地址位置之间的距离(以公里为单位)。
def calculate_distance(ip1, ip2): res1 = DbIpCity.get(ip1) res2 = DbIpCity.get(ip2) lat1, lon1 = res1.latitude, res1.longitude lat2, lon2 = res2.latitude, res2.longitude return distance((lat1, lon1), (lat2, lon2)).km# Input two IP addressesip_add_1 = input("1st IP: ") # 198.35.26.96ip_add_2 = input("2nd IP: ") # 220.158.144.59dist = calculate_distance(ip_add_1, ip_add_2)print(f"Distance between them is {str(dist)}km")
输出:
Enter 1st IP Address: 198.35.26.96Enter 2nd IP Address: 220.158.144.59Distance between them is 12790.62320788363km3. 计算您当前位置与服务器之间的距离
下面的代码将计算当前位置和给定 IP 地址位置之间的距离(以公里为单位)。
def get_distance_from_location(ip, lat, lon): res = DbIpCity.get(ip) ip_lat, ip_lon = res.latitude, res.longitude return distance((ip_lat, ip_lon), (lat, lon)).kmserver_ip = input("Server's IP: ")lat = float(input("Your Latitude: "))lng = float(input("Your Longitude: "))dist = get_distance_from_location(server_ip, lat, lng)print(f"Distance between the server and your location is {str(dist)}km")
输出:
Enter your server's IP Address: 208.80.152.201Enter your current location (Latitude): 26.4710Enter your current location (Longitude): 73.1134Distance between the server and your location is 12183.275099919923km
版权声明:
本站文章均来自互联网搜集,如有侵犯您的权益,请联系我们删除,谢谢。
标签: #python如何查看地址