Python 获取本机公网 IP

2023-05-02 16:59:16 浏览数 (1)

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

IPv4

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

直接返回ip地址
  • https://checkip.amazonaws.com/
  • https://ident.me
  • https://ifconfig.me/ip
  • http://icanhazip.com
  • https://api.ipify.org/
  • http://ip.42.pl/raw
Python 调用
代码语言:javascript复制
import requests
 
def get_external_ip():
    try:
        ip = requests.get('https://ident.me').text.strip()
        return ip
    except:
        return None

返回 json
  • http://jsonip.com/
  • http://ip.jsontest.com/
  • http://www.trackip.net/ip?json
  • https://ip.cn/api/index?ip=&type=0
  • http://ip.jsontest.com/
  • http://www.trackip.net/ip?json

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

示例返回值:

代码语言:javascript复制
{"ip":"168.138.188.194","country":"SG","geo-ip":"https://getjsonip.com/#plus","API Help":"https://getjsonip.com/#docs"}

Python 调用
代码语言:javascript复制
import requests
 
def get_external_ip():
    try:
        ip = requests.get("http://jsonip.com/").json().get('ip')
        return ip
    except:
        return None

其他返回格式
  • http://checkip.dyndns.org/

示例返回值:

代码语言:javascript复制
Current IP Address: 168.138.188.194

Python 调用
代码语言:javascript复制
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地址
  • https://v6.ident.me
Python 调用
代码语言:javascript复制
import requests

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

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

返回 json
  • http://jsonip.com/
代码语言:javascript复制
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)

  • http://ipv6.ipv6-test.ch/ip/?callback=?
代码语言:javascript复制
import requests

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

参考资料

  • https://blog.csdn.net/gotofor/article/details/127353218
  • https://zhuanlan.zhihu.com/p/220468105
  • https://blog.csdn.net/coco56/article/details/106725406/
  • https://www.cnblogs.com/boye169/p/17054914.html

0 人点赞