zoukankan      html  css  js  c++  java
  • 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:')
  • 相关阅读:
    poj1703
    poj 2385
    poj 3169 差分约束
    poj3723 最大权森林
    POJ3255 次短路
    图论算法----最小生成树
    给linux操作系统安装中文环境
    Windows下使用python
    pku3668 Game of Lines
    pku3670 Eating Together
  • 原文地址:https://www.cnblogs.com/kobewang/p/15330977.html
Copyright © 2011-2022 走看看