How to specify a specific NIC to be used in an application written in c++ (boost asio)

心不动则不痛 提交于 2019-12-07 06:44:51

问题


I have a machine connected to multiple independent networks, each on a different NIC (Network Interface Card). The machine runs Windows 7.

I run an application on the machine which needs to connect to a specific IP through a specific NIC, using TCP. The application uses c++11 and boost asio (1.53.0) for networking, and the source can be changed.

What are the different reasonable ways to solve this problem (specify endpoint IP and NIC) in a Windows environment?

The current solution assigns the respective (blocks of) IPs to the right NIC in the the routing table - by using the command line "route" command - as persistent routes. That way the OS handles the problem, which is allowed but not required.


回答1:


You should open() and bind() the socket to an endpoint before connecting. In this example I'm binding it to the loopback interface, in your scenario you can bind to the interface for your NIC.

#include <boost/asio.hpp>

int
main()
{
    using namespace boost::asio;
    io_service ios;
    ip::tcp::socket sock( ios );
    sock.open( ip::tcp::v4() );
    sock.bind( ip::tcp::endpoint(ip::address::from_string("127.0.0.1"), 0) );
    sock.connect( ip::tcp::endpoint(ip::address::from_string("127.0.0.1"), 1234) );
}

I'm not a Windows programmer so I can't provide a more detailed example than this. I believe you can enumerate through the NIC interfaces using GetAdaptersAddresses. On Linux I would use getifaddrs(3).



来源:https://stackoverflow.com/questions/17299476/how-to-specify-a-specific-nic-to-be-used-in-an-application-written-in-c-boost

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!