Python HTTPConnection bound to network interface
The web server I use at work are multi homed with the default route being the internal management network. We came across an issue where we wanted make a XMLHTTPRequest for a data feed from another company into our web app. We all know due to cross-site scripting attacks this is no longer possible so we had to write a little proxy script to pull the data and serve it from our own site. The standard python httplib doesn’t have the ability to bind to a specific interface so I have done a little sub-classing and now have a HTTPConnection which allows me to bind to a specific interface. Hope this helps someone as from my searching it seems to be a common request. You will meed to change the IP address to match your setup
import httplib import socket class HTTPConnectionInterfaceBound(httplib.HTTPConnection): """This class allows communication via a bound interface for multi network interface machines.""" def __init__(self, host, port=None, strict=None, bindip=None): httplib.HTTPConnection.__init__(self, host, port, strict) self.bindip = bindip def connect(self): """Connect to the host and port specified in __init__.""" msg = "getaddrinfo returns an empty list" for res in socket.getaddrinfo(self.host, self.port, 0, socket.SOCK_STREAM): af, socktype, proto, canonname, sa = res try: self.sock = socket.socket(af, socktype, proto) if self.debuglevel > 0: print "connect: (%s, %s)" % (self.host, self.port) if self.bindip != None : self.sock.bind ((self.bindip, 0)) self.sock.connect(sa) except socket.error, msg: if self.debuglevel > 0: print 'connect fail:', (self.host, self.port) if self.sock: self.sock.close() self.sock = None continue break if not self.sock: raise socket.error, msg conn = HTTPConnectionInterfaceBound('www.thegoldfish.org', 80, bindip='192.168.56.83') conn.request("GET", "/") r1 = conn.getresponse() print r1.status, r1.reason print r1.read()
Funkload (a performance testing tool written in Python) uses WebUnit, which in turn uses httplib to create connections, so we can’t bind virtual users to many IP addresses. I haven’t tried it yet but this snippet certainly points me in the right direction
Thanks!
Gaz