CWYAlpha

Just another WordPress.com site

Thought this was cool: 用Python指定HTTPConnection的出口IP(specify outgoing ip)

leave a comment »


描述:
客户端设置了多IP,想让不同的python脚本使用不同的IP访问远程服务器,怎么办?或者说如何用python指定出口IP(specify outgoing ip)?
解决:
真是花了我不少力气,被折腾死之后,发现python的socket是支持ip绑定的,用socket.bind就行了

再参考了这贴 http://bugs.python.org/issue3972

我写了个HTTPConnection_with_ip_binding的类,继承了httplib.HTTPConnection,修改了初始化,和conn ect函数,加了个参数bindip,试验成功,代码如下:

import httplib
import socket
class HTTPConnection_with_ip_binding(httplib.HTTPConnection):
    def __init__(self, host, port=None, strict=None,
                timeout=socket._GLOBAL_DEFAULT_TIMEOUT, bindip=None):
        httplib.HTTPConnection.__init__(self,host,port,strict,timeout)
        self.bindip = bindip
    def connect(self):
        msg = "getaddrinfo returns an empty list"
        for res in socket.getaddrinfo(self.host, self.port, 0,
                                      socket.SOCK_STREAM):
            af, socktype, proto, canonname, sa = res
            try:
               self.sock = socket.socket(af, socktype, proto)
               if self.debuglevel > 0:
                 print "connect: (%s, %s)" % (self.host, self.port)
               if self.bindip is not None:
                 self.sock.bind((self.bindip,0))
               self.sock.connect(sa)
            except socket.error, msg:
                if self.debuglevel > 0:
                    print 'connect fail:', (self.host, self.port)
                if self.sock:
                    self.sock.close()
                self.sock = None
                continue
            break
        if not self.sock:
            raise socket.error, msg
def testip():
    conn = HTTPConnection_with_ip_binding
(host="darwin.bio.uci.edu",bindip="64.13.223.117")
    conn.request("GET", "/cgi-bin/ipecho.pl")
    r1 = conn.getresponse()
    print r1.status, r1.reason
    data1 = r1.read()
    print data1
    conn.close()
if __name__=='__main__':
    testip()

执行发现返回了正确的ip

200 OK
<html><head>
<title>IP Echo</title>
</head>
<body><h2>Your Computer's IP Number</h2><dl>
<dt><b>REMOTE_ADDR</b>
<dd><i>64.13.223.117</i>
<dt><b>REMOTE_HOST</b>
<dd><i></i>
<dt><b>REMOTE_PORT</b>
<dd><i>36112</i>
</dl>
</body></html>


from duyamin’s blog: http://www.duyamin.com/2012/09/python-ip.html?utm_source=feedburner&utm_medium=feed&utm_campaign=Feed%3A+DuyaminsBlog+%28duyamin%E2%80%99s+blog%29

Written by cwyalpha

十一月 24, 2012 在 3:26 下午

发表在 Uncategorized

发表评论

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / 更改 )

Twitter picture

You are commenting using your Twitter account. Log Out / 更改 )

Facebook photo

You are commenting using your Facebook account. Log Out / 更改 )

Google+ photo

You are commenting using your Google+ account. Log Out / 更改 )

Connecting to %s

%d 博主赞过: