首页 > 解决方案 > 对于 Python 套接字,有没有办法设置使用的本地接口?

问题描述

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

标签: pythonsockets

解决方案


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

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))

推荐阅读