【问题标题】:For Python socket, is there a way to set the local interface used?对于 Python 套接字,有没有办法设置使用的本地接口?
【发布时间】:2021-05-21 21:59:27
【问题描述】:

我在一台带有 WiFi 和有线以太网的 Windows 笔记本电脑上使用 Python 套接字。 wifi 连接到互联网,有线以太网连接到没有互联网连接的本地网络。我希望套接字将数据发送到有线网络上的设备。如何强制套接字使用有线网络接口?套接字只能在 WiFi 关闭时向设备发送数据,所以我假设它会在 WiFi 接口可用时尝试使用它。

【问题讨论】:

    标签: python sockets


    【解决方案1】:

    您可以在连接之前将套接字绑定到特定接口:

    s = socket.socket()
    s.bind((local_interface_address, 0))
    s.connect((remote_addr, remote_port))
    

    也可以使用create_connection方法的源地址参数:

    s = socket.socket()
    s.create_connection((remote_addr, remote_port),
                        source_address=(local_interface_address, 0))
    

    【讨论】:

    • 我尝试了这两种方法,它杀死了打开和关闭 wifi 的有线连接。
    猜你喜欢
    • 2020-03-19
    • 2013-05-22
    • 2010-10-25
    • 2011-04-29
    • 2020-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-11
    相关资源
    最近更新 更多