how to check if connection is established when use libev with non-block socket

三世轮回 提交于 2019-12-11 02:07:04

问题


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?


回答1:


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
}


来源:https://stackoverflow.com/questions/16074981/how-to-check-if-connection-is-established-when-use-libev-with-non-block-socket

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!