惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
博客园 - 聂微东
博客园 - 叶小钗
爱范儿
爱范儿
罗磊的独立博客
Hugging Face - Blog
Hugging Face - Blog
阮一峰的网络日志
阮一峰的网络日志
S
SegmentFault 最新的问题
Apple Machine Learning Research
Apple Machine Learning Research
美团技术团队
T
Tailwind CSS Blog
博客园 - 司徒正美
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
宝玉的分享
宝玉的分享
量子位
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
The Cloudflare Blog
人人都是产品经理
人人都是产品经理
小众软件
小众软件
博客园 - 【当耐特】
博客园 - 三生石上(FineUI控件)
V
Visual Studio Blog
雷峰网
雷峰网
酷 壳 – CoolShell
酷 壳 – CoolShell

又见苍岚

COLMAP PatchMatch Stereo 算法详解 事件驱动的状态机框架:从理论到工程实践 Git 在国内网络环境下无法 Push 的排查与修复 —— 配置 Clash 代理 分段五次多项式插值原理详解 路径插值方法深度对比研究 Claude Code 使用指南 OpenClaw 记忆管理与技能创建指南 CBS(Conflict-Based Search)算法详解 A* 算法及其变种详解 OpenClaw 配置多 Agents Windows Powershell 无法加载文件,因为在此系统上禁止运行脚本问题的解决方案 MaxClaw 安装流程 大模型 AI 名词介绍 AList 网盘聚合工具简介 Protobuf 简介与测试 Claude Code 简介以及 GLM 4.7 模型接入 Github 歌词下载工具 163MusicLyrics Python __getattr__ 懒加载 Python TypedDict 机器人仿真平台 Gazebo 安装记录 机器人仿真平台 Gazebo 简介 多机器人路径规划问题(Multi-Agent Path Finding, MAPF)简介 Python exifread 读取修改过的 jpeg 信息错误问题修复 3D 坐标系变换的理解 3D 旋转矩阵基本概念 MongoDB Compass 介绍 Python 环境管理工具 uv Flutter 开发指南 Snipaste 安装下载与黑屏问题解决方案 全局路径规划算法记录
Python 获取本机公网 IP
Yiwei Zhang · 2023-04-27 · via 又见苍岚

有很多大佬搭建的查询本机公网 IP 的服务,本文记录相关内容。

IPv4

可以访问获取公网 IPv4 IP 的站点:

直接返回ip地址

Python 调用
1
2
3
4
5
6
7
8
import requests

def get_external_ip():
try:
ip = requests.get('https://ident.me').text.strip()
return ip
except:
return None

返回 json

http://jsonip.com/ 在有 IPv6 地址时会优先返回 IPv6 地址

示例返回值:

1
{"ip":"168.138.188.194","country":"SG","geo-ip":"https://getjsonip.com/#plus","API Help":"https://getjsonip.com/#docs"}
Python 调用
1
2
3
4
5
6
7
8
import requests

def get_external_ip():
try:
ip = requests.get("http://jsonip.com/").json().get('ip')
return ip
except:
return None

其他返回格式

示例返回值:

1
Current IP Address: 168.138.188.194
Python 调用
1
2
3
4
5
6
7
8
import requests
import re

url = "http://checkip.dyndns.org"
proxies={'http':'127.0.0.1:****'}
theIP = requests.get(url,proxies=proxies).text

print("your IP Address is: ", theIP)

IPv6

不支持 IPv6 的网络环境下无法访问

直接返回ip地址

Python 调用
1
2
3
4
5
6
7
8
import requests

def getIPv6Address():
text = requests.get('https://v6.ident.me').text
return text

if __name__ == "__main__":
print(getIPv6Address())

返回 json

1
2
3
4
5
6
7
8
9
10
11
12
import requests

def get_external_ip():
try:
ip = requests.get("http://jsonip.com/").json().get('ip')
return ip
except:
return None

if __name__ =="__main__":
ip = get_external_ip()
print(ip)

1
2
3
4
5
6
import requests

pageURL='http://ipv6.ipv6-test.ch/ip/?callback=?'
content=requests.get(pageURL).text.strip("callback")
data = eval(content)
print(data['ip'])

参考资料

文章链接:
https://www.zywvvd.com/notes/coding/internet/get-local-ip/get-local-ip/