以 posix 方式绑定到特定网卡
我的计算机上有 3 个网络接口 (eth0-2),每个接口都有自己的网络子网 192.168.10.、192.168.20.、192.168.30.。我想知道如何使用 BSD 套接字侦听特定 NIC 的端口,例如侦听 eth1 的端口 10000(192.168.20。),目前我得到的似乎是列表/绑定仅限 eth0。我当前使用的操作系统是 Ubuntu,但我希望该解决方案能够在任何 posix 系统上工作/移植。
顺便说一句,我正在用 C++ 开发我的应用程序,并且希望获得有关 C++ 网络库的一些指导,我已经查看过 Qt,但是该许可证不适合我正在进行的开发类型。
I have 3 network interfaces on my machine (eth0-2) each one has its own network subnet 192.168.10.,192.168.20.,192.168.30.. I was wondering how does one using BSD sockets listen on a port for a specific NIC, For example listen on port 10000 for eth1 (192.168.20.), At the moment I've got that seems to list/bind to eth0 only. The OS I'm currently using is Ubuntu, but I would like the solution to work/portable on any posix system.
On a side note I'm developing my application in C++, and would appreciate some guidance on networking libraries in C++, I've had a look at Qt however the license is not suitable for the type of development I'm doing.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
bind() 系统调用允许您指定要将套接字绑定到的地址。您可以绑定到特定地址,也可以绑定到 INADDR_ANY,它将侦听所有传入地址,无论接口如何。
至于网络库,boost::asio 很好。当然,您可能想要指定比“网络库”更多的要求以获得更好的推荐。
The bind() system call lets you specify the address to bind the socket to. You can bind to a specific address, or you can bind to INADDR_ANY, which will listen on all incoming addresses, regardless of interface.
As for network libraries, boost::asio is good. Of course, you might want to specify more requirements than "a networking library" to get a better recommendation.
如果您将单个侦听套接字绑定到主机上的所有 IP(例如,在端口 10000 上),我不相信存在通用机制来确定特定 的 IP 地址>ACCEPT-ed 连接进来。
一种解决方案是为您的 3 个 IP 地址中的每一个BIND一个单独的套接字,然后使用SELECT来监视传入的连接连接。这样您将始终知道使用了哪个传入 IP 地址。
作为替代方案,如果您可以完全控制客户端协议,则可以设计一个要求,即客户端在建立套接字连接后立即传输使用的目标 IP。这将允许您使用单个服务器套接字来侦听所有传入连接,但需要您信任客户端提供的信息。
If you BIND a single listening socket to all the IPs on the host (on port 10000, for example), I do not believe there is a general mechanism to determine the IP address on which a particular ACCEPT-ed connection came in.
One solution is to BIND a separate socket to each of your 3 IP addresses, and then use SELECT to watch for incoming connections. That way you'll always know which incoming IP address was used.
As an alternative, if you have full control over the client-side protocol, you could design in a requirement that the client transmits the target IP that was used immediately after establishing a socket connection. That would allow you to use a single server socket to listen for all incoming connections, but would require you to trust the information that the client was providing.