您可以定义一个字典映射线程标识符到 IP 地址或使用threading.local()
全局对象为每个线程定义它:
socket_data = threading.local()
socket_data = bind_ip = None
true_socket = socket.socket
def bound_socket(*a, **k):
sock = true_socket(*a, **k)
if socket_data.bind_ip is not None:
sock.bind((socket_data.bind_ip, 0))
return sock
socket.socket = bound_socket
def thread_target(bind_ip):
socket_data.bind_ip = bind_ip
# the rest code
for bind_ip in [...]:
thread = Thread(target=thread_target, args=(bind_ip,))
# ...
但请注意,这是相当肮脏的黑客行为。更好的方法是扩展connect()
子类中的方法HTTPConnection
并重新定义http_open()
子类中的方法HTTPHandler
。