客户端设置了多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>
相关推荐: MySQL导入导出数据库备份还原 – mysqldump
mysqldump [OPTIONS] database [tables] 如果不给定任何表,整个数据库将被导出。备份MySQL数据库的命令mysqldump -hhostname -uusername -ppassword databasename >…
请登录后发表评论
注册