python socket监听端口_python - socket - client端指定ip和端口

问题描述:

在设备中有3个NI, ip分别为192.168.1.5/6/7。其中本端192.168.1.6同对端192.168.1.10建立了一个tunnel。

我希望测试tunnel连通性, 对端起一个socket server。本段作为client。

但是如果本端client直接连接,使用的源ip为192.168.1.5,端口随机。

我的迷惑在寻找一个指定ip的函数,在看了python的manual document中socket部分看了一遍后,没有找到这个函数。

随后我意识到我的一个思维误区:bind()函数

bind(address)之前作为socket server的一部分,启动时候使用制动server的ip和端口

但是bind在客户端一样的作用。指定socket建立链接时使用的ip和端口。

代码:

def start_tcp_client(ip, port):

#server port and ip

server_ip = ip

servr_port = port

tcp_client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

try:

tcp_client.bind(('192.168.1.6', 11560))

tcp_client.connect((server_ip, servr_port))

except socket.error:

print 'fail to setup socket connection'

else:

print 'sending..........'

tcp_client.sendall("echo message")

print 'reading...........'

print tcp_client.recv(1024)

tcp_client.close()

搞定!

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值