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

推荐订阅源

Microsoft Security Blog
Microsoft Security Blog
Jina AI
Jina AI
量子位
博客园 - 叶小钗
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
IT之家
IT之家
S
SegmentFault 最新的问题
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
小众软件
小众软件
Hugging Face - Blog
Hugging Face - Blog
雷峰网
雷峰网
博客园 - 聂微东
美团技术团队
Last Week in AI
Last Week in AI
罗磊的独立博客
酷 壳 – CoolShell
酷 壳 – CoolShell
博客园 - 三生石上(FineUI控件)
WordPress大学
WordPress大学
宝玉的分享
宝玉的分享
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
博客园_首页
V
Visual Studio Blog
大猫的无限游戏
大猫的无限游戏
The Cloudflare Blog

博客园 - kobe

.Net Razor Ajax Post Get处理 .net 7 session支持 windows redis常用 GO语言Windows安装和VScode配置 ASP.NET CORE 托管IIS第一次访问慢 .netcore发布托管IIS后 swagger显示404 dotnet run .net core web html中午查看源码显示乱码 centos netcore开机启动 NetCore Razor 路由伪静态设置 net core 6.0 session支持,非controller引用session net core web项目(net 6.0)增加apicontroller JPush,Jverify,JCore Ios冲突 apiRecord:methodName service mysqld restart 无效 Python log Python Flask+Windows Service制作 Windows下删除.svn文件夹 C# LINQ list遍历并组装返回新查询 windows server 2016下360wifi安装
Python获取本机多IP并指定出口IP
kobe · 2021-09-24 · via 博客园 - kobe

1.添加引用

import requests,sys,socket
#获取本机IP地址
def getIPList(self):
ipList=[]
# 下方代码为获取当前主机IPV4 和IPV6的所有IP地址(所有系统均通用)
addrs = socket.getaddrinfo(socket.gethostname(), None)
# 同上仅获取当前IPV4地址
for item in addrs:
if ':' not in item[4][0]:
if item[4][0].startswith('192.') or item[4][0].startswith('10.'): #排除内网
continue
else:
print('当前主机IPV4地址为:' + item[4][0])
ipList.append(item[4][0])
return ipList
 #获取一个随机IP
def getRandIP(self,ipList):
rand=random.randint(0,len(ipList)-1)
print('随机数:'+str(rand))
return ipList[rand]
2.指定出口IP
from requests_toolbelt.adapters import source
ipList=self.getIPList()
if len(ipList)>0:
new_source = source.SourceAddressAdapter(self.getRandIP(ipList))
session.mount('http://', new_source)
session.mount('https://', new_source)
try:
r = session.get(url, headers=headers)
print('first request:')
#print(r.text)
except:
print('except:')