python - 对于 Python 套接字,有没有办法设置使用的本地接口?
问题描述
我在带有 WiFi 和有线以太网的 Windows 笔记本电脑上使用 Python 套接字。wifi 连接到互联网,有线以太网连接到没有互联网连接的本地网络。我希望套接字将数据发送到有线网络上的设备。如何强制套接字使用有线网络接口?套接字只能在 WiFi 关闭时向设备发送数据,所以我假设它会在 WiFi 接口可用时尝试使用它。
解决方案
您可以在连接之前将套接字绑定到特定接口:
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))
推荐阅读
- mysql - 如何计算时钟重置时的持续时间?
- node.js - MERN : Multiple independent react apps without involving to web pack details
- internet-explorer - 在 DNS / 类似级别检测 Internet Explorer?
- arrays - 为什么在初始化指针时必须将数组转换为 type[]?
- c# - C# 在多个 if(s) 中嵌套多个 try(s) 然后执行 catch(s) 之后?
- c++ - 在这种情况下是 clang 错误、gcc 错误还是两者都错误 - 用成员指针抛弃 constness
- php - 使用 Xdebug 进行远程调试会导致 PHP 脚本执行停止
- sql - 在 Hive 中将时间戳 (HH:mm:ss) 转换为秒的任何更好的方法
- javascript - 在加载时反应渲染,但在异步调用完成时不更新
- javascript - 我可以直接从 HTML 将 HTML 元素传递给 oninput 属性中定义的函数吗?