使用libev与非块套接字时如何检查是否建立了连接

时间:2013-04-18 05:15:27

标签: sockets libev

我有一些代码使用libev来解决如何处理连接超时问题(请参阅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(...)

并在某个地方执行ev_run。调用connect_cb,在这个回调函数中,我用EV_ERROR检查了revents,结果没有错误。这很奇怪,因为我提供了一个无效的端口号,这个端口号没有在本地机器上监听。无论如何,我尝试在connect_cb函数中发送消息,得到错误111,这意味着连接被拒绝。我糊涂了!如何在使用非阻塞套接字时检查连接是否正确建立?

1 个答案:

答案 0 :(得分:1)

如果连接发生错误,

getsockopt是可能获得的方法:

int err;
socklen_t len = sizeof(err);
getsockopt(sd, SOL_SOCKET, SO_ERROR, &err, &len);
if (err) {
    // error happen
} else {
    connection is OK
}