Python获取本机多IP并指定出口IP

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:')

posted on 2021-09-24 16:25  kobe  阅读(967)  评论(0编辑  收藏  举报

导航