Created
November 20, 2012 11:55
-
-
Save anonymous/4117504 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- 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