When connecting to a socket with ASIO, you need to (1) create the socket; (2) open()
it; (3) connect()
it.
boost::asio::io_context io_context;
// (1) create socket
boost::asio::ip::tcp::socket socket(io_context);
// (2) open it
boost::system::error_code open_error;
socket.open(open_error);
if (open_error) { /* .... */ }
// (3) connect
boost::system::error_code connect_error;
boost::asio::ip::tcp::endpoint endpoint(
boost::asio::ip::address::from_string("1.2.3.4"), 12345);
socket.connect(endpoint, connect_error);
if (connect_error) { /* .... */ }
It's pretty clear that the connect()
call could fail. It's an actual networking operation, and the remote endpoint might be inaccessible, or refuse the connection, etc.
But can the open()
call fail? If so, what would cause that? It doesn't seem to do much, and certainly not access the network. I think perhaps if the process is out of file descriptors then that could cause it to fail - does that seem right?
A similar question applies to sockets passed to acceptor.accept()
instead of connecting outbound. More to the point it applies to the acceptor
class itself: you have to open it before calling its accept()
method. Can that fail?
(For both sockets and acceptors it's possible to open as part of the constructor by passing in the relevant parameters. But then the documentation says that they can throw an exception, so the same question still applies.)