Question

I have some code use libev on how to deal with connection timeout as below (please refer to http://lists.schmorp.de/pipermail/libev/2011q2/001365.html):

sd = create_socket()
set_socket_nonblock(sd)
connect("127.0.0.1", port) // connect to an invalid port
ev_io_init(&w_io, connect_cb, sd, EV_WRITE)
ev_io_start(...)
ev_timer_init(&w_timer, timeout_cb, 5.0, 0)
ev_timer_start(...)

and in someplace perform ev_run. The connect_cb is called and in this callback function I checked the revents with EV_ERROR, the result is no error. This is strange because I provide an invalid port number which is not listening in local machine. Anyway, I try to send a message in the connect_cb function, got an error 111, which means that connection refused. I'm confused! How to check if the connection is established correctly when use non-block socket?

Was it helpful?

Solution

getsockopt is possible way to get if the connection has some error happen:

int err;
socklen_t len = sizeof(err);
getsockopt(sd, SOL_SOCKET, SO_ERROR, &err, &len);
if (err) {
    // error happen
} else {
    connection is OK
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top