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.
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)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With