Skip to content

Instantly share code, notes, and snippets.

@whille
Created August 30, 2024 17:55
Show Gist options
  • Save whille/a8bcfcdbc1c6496d603f732fb009095d to your computer and use it in GitHub Desktop.
Save whille/a8bcfcdbc1c6496d603f732fb009095d to your computer and use it in GitHub Desktop.
test gevent bind ip , in python2, urllib2
#!/usr/bin/env python
import gevent.monkey
gevent.monkey.patch_all()
import gevent.socket as socket
#import socket
from gevent.pool import Pool
import logging
import urllib2
def http_time(url, source_ip):
def bound_socket(*a, **k):
try:
sock = true_socket(*a, **k)
sock.bind((source_ip, 0))
return sock
except Exception as e:
logging.warn("cannot bind source_ip: %s, e: %s" % (source_ip, e))
true_socket = socket.socket
socket.socket = bound_socket
try:
# AIO
response = urllib2.urlopen(url)
print(source_ip, 'result:', response.code, len(response.read()))
finally:
socket.socket = true_socket
def batch():
pool = Pool(10)
jobs = list()
url = 'http://www.example.com'
fake_ips = ["%s.0.0.1" % i for i in (range(1, 10))]
for source_ip in fake_ips:
jobs.append(pool.spawn(http_time, url, source_ip))
pool.join(timeout=10)
pool.kill()
if __name__ == '__main__':
batch()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment