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

倾然丶 夕夏残阳落幕 提交于 2019-12-05 11:02:56

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

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