Binding boost asio to local tcp endpoint

2019-02-26 01:53发布

问题:

I'm trying to bind a boost asio tcp socket to a local network interface specifically. When is the correct time to call the bind() method on the socket?

_endpoint points to the remote ip/port, e.g. 192.168.0.15:8888.

// Invoke async. connect. Immediate return, no throw.
_socket.async_connect(_endpoint,
boost::bind(&MyTransceiver::handleConnect, this,
    boost::asio::placeholders::error));

Within MyTransceiver::handleConenct(), I tried the following code:

boost::asio::ip::tcp::endpoint local_end_point(
        boost::asio::ip::address::from_string("192.168.0.55"), 6543 );

    _socket.bind(local_end_point);

Calling it here fails, calling it before the async_connect() call also, with a "invalid handle" exception.

回答1:

Looks like there isn't enough information. But generally, you should:

_socket->open()

_socket->set_option()

_socket->bind()

_socket->async_connect()

in handleConnect(): _socket->async_read_some()