Skip to content

Instantly share code, notes, and snippets.

Created November 20, 2012 11:55
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/4117504 to your computer and use it in GitHub Desktop.
Save anonymous/4117504 to your computer and use it in GitHub Desktop.
# -*- coding: utf-8 -*-
'''
可切换本地服务器IP访问目标服务
'''
import urllib2, httplib, socket
random_ip = '192.168.1.1'
class BindableHTTPConnection(httplib.HTTPConnection):
def connect(self):
"""Connect to the host and port specified in __init__."""
self.sock = socket.socket()
self.sock.bind((self.source_ip, 0))
if isinstance(self.timeout, float):
self.sock.settimeout(self.timeout)
self.sock.connect((self.host,self.port))
def BindableHTTPConnectionFactory(source_ip):
def _get(host, port=None, strict=None, timeout=0):
bhc=BindableHTTPConnection(host, port=port, strict=strict, timeout=timeout)
bhc.source_ip=source_ip
return bhc
return _get
class BindableHTTPHandler(urllib2.HTTPHandler):
def http_open(self, req):
return self.do_open(BindableHTTPConnectionFactory(random_ip), req)
opener = urllib2.build_opener(BindableHTTPHandler)
opener.open("http://google.com/").read()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment