本文最后更新于:2024年1月14日 晚上

有很多大佬搭建的查询本机公网 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/


“觉得不错的话,给点打赏吧 ୧(๑•̀⌄•́๑)૭”

微信二维码

微信支付

支付宝二维码

支付宝支付

Python 获取本机公网 IP
https://www.zywvvd.com/notes/coding/internet/get-local-ip/get-local-ip/
作者
Yiwei Zhang
发布于
2023年4月27日
许可协议