V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
yuexiande
V2EX  ›  Python

如何实现 request 指定使用出口 ip

  •  
  •   yuexiande · 2016-03-27 22:41:53 +08:00 · 3019 次点击
    这是一个创建于 2943 天前的主题,其中的信息可能已经有所发展或是发生改变。
    如何实现 request 指定使用出口 ip ,我的服务器网卡有多个 ip ,
    默认是一个地址,但是如何使用其他的网卡 ip , request 访问网站
    2 条回复    2016-04-05 18:29:56 +08:00
    setiepr
        1
    setiepr  
       2016-04-05 18:29:20 +08:00
    setiepr
        2
    setiepr  
       2016-04-05 18:29:56 +08:00
    import socket

    real_create_conn = socket.create_connection

    def set_src_addr(*args):
    address, timeout = args[0], args[1]
    source_address = ('IP_ADDR_TO_BIND_TO', 0)
    return real_create_conn(address, timeout, source_address)

    socket.create_connection = set_src_addr

    import requests
    r = requests.get('http://www.google.com')
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5648 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 03:19 · PVG 11:19 · LAX 20:19 · JFK 23:19
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.