0

I connected a non-existent address using tcp::socket::connect method and it returned WSAETIMEDOUT(10060) as expected. But why invoking tcp::socket::is_open() returned 1(true) ? I think it should return 0(false), because of establishing connection failed.

int main(int argc, char* argv[]) {
    boost::asio::io_context context;
    tcp::socket socket(context);
    /*non-existent address 111.111.111.111:8080*/
    tcp::endpoint endpoint(address::from_string("111.111.111.111"), 8080);
    error_code result_error;
    socket.connect(endpoint, result_error);

    /* error code: WSAETIMEDOUT [10060]
    *  description: established connection failed because connected host has failed to respond
    */
    std::cout << "error code: " << result_error.value()<< result_error.message() << std::endl;

    /*returned 1*/
    std::cout << "is_open returned: "<< socket.is_open() << std::endl;
}

I expect the output of is_open to be 0, but the actual output is 1.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
icewall
  • 41
  • 4
  • as this boost documentation, the is_open function just check the socket is open. https://www.boost.org/doc/libs/1_66_0/doc/html/boost_asio/reference/basic_stream_socket/is_open.html – moinmaroofi May 27 '19 at 09:45

1 Answers1

0

The is_open function just check if the socket is "open" (the open function have been successfully called), not if the socket is connected.

In short, is_open checks socket creation status, not socket connection status.

If you see this old SO answer it will tell you that it's impossible to know the connection status, and also gives a workaround (keep the connection status yourself).

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • 1
    It would have also been prudent to check that `error_code` from `connect`. – rustyx May 27 '19 at 07:37
  • thanks, currently, I close socket every time getting error from invoking connect/read/write methods, which makes is_open equals to is_connected – icewall May 28 '19 at 01:21