boost::asio::ip::tcp::resolver::resolve() blocks forever

Daniel Sloof picture Daniel Sloof · Mar 24, 2009 · Viewed 7.7k times · Source

I'm trying to create something similar as this code found at the boost.asio examples.

socket.h:

class some_class {
private:
    ...
        boost::asio::io_service io_service;
public:
        some_class() {
             /* This stuff isn't used in the example...
               ...but it doesn't change anything... */
             io_service.run();
        }
};

socket.cpp:

using boost::asio::ip::tcp;

bool some_class::connect(char* host, char* port) 
{
    printf("Resolving hostname...\n");

    /* Resolve hostname. */
    tcp::resolver resolver(io_service);
    tcp::resolver::query query(tcp::v4(), host, port);
    tcp::resolver::iterator iterator = resolver.resolve(query);

    printf("Connecting to %s:%s... ", host, port);

    /* Connect to resolved hosts. */
    sock->connect(*iterator);

    return true;
}

g++ builds this without any errors, but the code never makes it past the resolver.resolve() call.
I've tried both "127.0.0.1" and "localhost" for host and "80" for port. (don't think it should matter, but apache2 is up and running)

When I ctrl+c out of my application, it obviously terminates but it does output the "Connecting to string" just before it does.

I am planning on building the example myself and seeing if the same problem occurs, and will definitely post the results here. Has anyone encountered this issue or knows what could possibly cause this behavior?

edit:
The example runs just fine... I have some debugging to do I suppose.

second edit:
I don't get it, the only thing that could be different is host/port.
Example uses char* argv[] and I'm using:

char host[] = "localhost";
char port[] = "80";

third edit:
it indeed seems to be blocking at connect, forgot to fflush(stdout). then it has to be a problem with the socket. going to do some more testing.

fourth edit:
stupid me, it wasn't blocking at all! I was just relying too much on console output..

Answer

camh picture camh · Mar 24, 2009

It is probably blocking on the call to connect, after the printf.

stdout is line buffered by default, and since you do not have a \n at the end of your printf string, you will not see its output. When you kill the program, the buffer is being flushed, which is why you see the message then.