The code below binds an ip address to urllib, urllib2, etc.
import socket
true_socket = socket.socket
def bound_socket(*a, **k):
sock = true_socket(*a, **k)
sock.bind((sourceIP, 0))
return sock
socket.socket = bound_socket
Is it also able to bind an ip address to telnetlib?
telnetlibat least in recent Python releases usessocket.create_connection(see telnetlib’s sources here) but that should also be caught by your monkeypatch (sources here — you’ll see it uses a bare identifiersocketbut that’s exactly in the module you’re monkeypatching). Of course monkeypatching is always extremely fragile (the tiniest optimization in some future release, hoisting the global lookup ofsocketincreate_connection, and you’re toast…;-) so maybe you’ll want to monkeypathcreate_connectiondirectly as a modestly-stronger approach.