Configuring requests module to use secondary IP on server for outbound requests - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: Networking (https://python-forum.io/forum-12.html) +--- Thread: Configuring requests module to use secondary IP on server for outbound requests (/thread-622.html) |
Configuring requests module to use secondary IP on server for outbound requests - mohit - Oct-24-2016 Hello all. I have a server which has two IP addresses - primary and secondary. I have written a python script on server which keeps calling a remote service as HTTP request through "requests" module. By default it uses primary IP of server. My question is, is there a way to make script use other IP of server for all outbound requests randomly? Server uses OpenVZ for virtual infrastructure and I can change ip for outbound requests manually via SolusVM control panel but Can I configure script such that it starts using other ip for outbound requests dynamically? If not, is it possible to setup a proxy server (script running as daemon) on this server which uses this other IP for outbound requests and then I can use this service running on a port as "proxy" in my requests module call? RE: Configuring requests module to use secondary IP on server for outbound requests - nilamo - Oct-24-2016 Because of the way sockets are made in python, you have to kind of do it yourself. From StackOverflow: http://stackoverflow.com/a/1150423 Wrote:Unfortunately the stack of standard library modules in use (urllib2, httplib, socket) is somewhat badly designed for the purpose -- at the key point in the operation, HTTPConnection.connect (in httplib) delegates to socket.create_connection, which in turn gives you no "hook" whatsoever between the creation of the socket instance sock and the sock.connect call, for you to insert the sock.bind just before sock.connect that is what you need to set the source IP (I'm evangelizing widely for NOT designing abstractions in such an airtight, excessively-encapsulated way -- I'll be speaking about that at OSCON this Thursday under the title "Zen and the Art of Abstraction Maintenance" -- but here your problem is how to deal with a stack of abstractions that WERE designed this way, sigh). |