准备工作:安装必备工具
首先,请确保你的python环境中安装了requests库。
pip install requests
第一步:查询自己的公网 ip 信息
import requests
import json
# 向ipinfo.io发送请求,不带任何ip地址,它会默认查询你自己的ip
url = "https://ipinfo.io/json"
try:
response = requests.get(url)
response.raise_for_status() # 如果请求失败 (如状态码 4xx, 5xx), 会抛出异常
# 将返回的json格式数据解析为python字典
data = response.json()
print("--- 你的ip信息详情 ---")
# 为了美观,使用json.dumps进行格式化输出
print(json.dumps(data, indent=4, ensure_ascii=false))
except requests.exceptions.requestexception as e:
print(f"请求失败: {e}")
运行后,你将看到类似这样的输出(信息会根据你的实际情况而变):
{
"ip": "xxx.xxx.xxx.xxx",
"hostname": "some.host.name",
"city": "xx",
"region": "xx",
"country": "cn",
"loc": "39.9042,116.4074",
"org": "xx",
"postal": "100000",
"timezone": "asia/shanghai",
"readme": "https://ipinfo.io/missingauth"
}
第二步:查询任意指定的 ip 地址
我们可以查询任何一个我们想查的公网ip,比如谷歌的公共dns服务器 8.8.8.8。
import requests
import json
# 定义要查询的ip地址
target_ip = "8.8.8.8"
# 构造请求url,将ip地址拼接到url中
url = f"https://ipinfo.io/{target_ip}/json"
try:
response = requests.get(url)
response.raise_for_status()
data = response.json()
print(f"--- ip: {target_ip} 的信息详情 ---")
print(json.dumps(data, indent=4, ensure_ascii=false))
except requests.exceptions.requestexception as e:
print(f"请求失败: {e}")
输出将会是:
{
"ip": "8.8.8.8",
"hostname": "dns.google",
"city": "mountain view",
"region": "california",
"country": "us",
"loc": "37.4056,-122.0775",
"org": "as15169 google llc",
"postal": "94043",
"timezone": "america/los_angeles",
"readme": "https://ipinfo.io/missingauth",
"anycast": true
}
第三步:自由封装成自己需要的内容显示库
示例
import requests
def get_ip_info(ip_address: str) -> dict | none:
"""
查询指定ip地址的详细信息。
:param ip_address: 要查询的ip地址字符串。
:return: 包含ip信息的字典,如果查询失败则返回none。
"""
url = f"https://ipinfo.io/{ip_address}/json"
try:
response = requests.get(url, timeout=5) # 增加超时设置
response.raise_for_status()
return response.json()
except requests.exceptions.requestexception as e:
print(f"查询ip {ip_address} 时出错: {e}")
return none
# --- 使用我们封装好的函数 ---
if __name__ == "__main__":
ip_list = ["8.8.8.8", "1.1.1.1", "114.114.114.114"]
for ip in ip_list:
info = get_ip_info(ip)
if info:
country = info.get('country', 'n/a')
city = info.get('city', 'n/a')
org = info.get('org', 'n/a')
print(f"ip: {ip:<15} | location: {country}, {city} | organization: {org}")
方法补充
python 获取本机ip地址的多种方法
方法一: 通常使用socket.gethostbyname()方法即可获取本机ip地址,但有时候获取不到(比如没有正确设置主机名称),示例代码如下:
import socket # 获取本机计算机名称 hostname = socket.gethostname() # 获取本机ip ip = socket.gethostbyname(hostname) print(ip)
方法二: 亲测本方法在windows和linux系统下均可正确获取ip地址
import socket
def get_host_ip():
"""
查询本机ip地址
:return: ip
"""
try:
s = socket.socket(socket.af_inet, socket.sock_dgram)
s.connect(('8.8.8.8', 80))
ip = s.getsockname()[0]
finally:
s.close()
return ip
if __name__ == '__main__':
print(get_host_ip())到此这篇关于使用python查询自己或任意指定的ip地址的文章就介绍到这了,更多相关python查询ip地址内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论