• 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:')
  • 相关阅读:
    Session的配置
    插件编程小窥
    今日遇到了困难,顺便看了下SMO
    初识三层架构
    .NET文件类库
    JQuery学习笔记
    反射整理学习<二>
    通俗道破单例模式
    菜鸟写代码生成器最后一天完结篇
    卧谈会:委托与事件
  • 原文地址:https://www.cnblogs.com/kobewang/p/15330977.html
Copyright © 2020-2023  润新知