To bind to a specific interface you have to open the connection first. You do that - so far so good. But after that you call boost::asio::connect(socket, remoteEndpoint);
which will close the connection for you (as a service so to say).
Boost tells you that it does so - but you have to look closely. In the reference under parameters for the overloaded version of connect
you are using it will say
Parameters
s
The socket to be connected. If the socket is already open, it will be closed.
or in its implementation in boost/asio/impl/connect.hpp:
// Copyright (c) 2003-2011 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
[...]
template <typename Protocol, typename SocketService,
typename Iterator, typename ConnectCondition>
Iterator connect(basic_socket<Protocol, SocketService>& s,
Iterator begin, Iterator end, ConnectCondition connect_condition,
boost::system::error_code& ec)
{
ec = boost::system::error_code();
for (Iterator iter = begin; iter != end; ++iter)
{
iter = connect_condition(ec, iter);
if (iter != end)
{
s.close(ec);
s.connect(*iter, ec);
if (!ec)
return iter;
}
}
if (!ec)
ec = boost::asio::error::not_found;
return end;
}
(note the s.close(ec);
)
The solution
should be simple. Replace boost::asio::connect...
by
socket.connect(*remoteEndpoint);
(or a loop over the respective remote endpoints, similar to the boost sourcecode, if necessary.)