I have a C++ boost client that does a blocking connect and processes the message once it receives a response. I am facing a strange issue.
tcp::resolver::query query(tcp::v6(), this->host, port,tcp::resolver::query::v4_mapped);
iterator = resolver.resolve(query);
socket = new tcp::socket(io_service);
socket->connect(*iterator);
I tried to connect to a machine that was not reachable by ping6 (but was IPV6 enabled). Still, I didn't get any error while trying to resolve the query in line-2. As a result of this, it takes too much time while attempting a connection before giving an error. My questions:-
1) Is it possible to timeout on a blocking connect from asio? I cannot switch to async mode of operation.
2) How come I don't get an error while it resolves an unreachable host?
Any advice would be very much helpful
Timeouts are the wrong place for synchronous methods, there's a lengthy discussion in the asio ticket tracker.
I cannot switch to async mode of
operation.
I find this highly unlikely given the timeout requirement, post the rest of your code and explain why you cannot use asynchronous operations.
When this question was asked, I guess ASIO did not have any example on how to accomplish what the OP needed, that is to timeout a blocking operation such as a blocking socket operation. Now there exists examples to show you exactly how to do this. the example seems long, but that is because it is WELL commented. It shows how to use the ioservice in a 'one shot' kind of mode.
I think the example is a great solution. The other solutions here break portability and don't take advantage of ioservice. if portability is not important and the ioservice seems like to much overhead --THEN-- you should not be using ASIO. No matter what, you will have an ioservice created (almost all ASIO functionality depends on it, even sync sockets) so, take advantage of it.
ASIO example of timeout on blocking call
The ASIO documentation has been updated, so check it out for new examples on how to overcome some of the 'gotchas' ASIO use to have.