python

问题描述:

在设备中有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()

  

搞定!

原文地址:https://www.cnblogs.com/felixwa/p/6064459.html