To make a non-blocking connection () if the socket has already been non-blocked:
int res = connect(fd, ...); if (res < 0 && errno != EINPROGRESS) {
In the second case, when connect () failed with EINPROGRESS (and only in this case), you need to wait until the socket is writable, for example. for epoll, indicate that you expect EPOLLOUT on this socket. After you receive a notification that it is writable (with epoll, also expect to receive an EPOLLERR or EPOLLHUP event), check the result of the connection attempt:
int result; socklen_t result_len = sizeof(result); if (getsockopt(fd, SOL_SOCKET, SO_ERROR, &result, &result_len) < 0) {
In my experience, on Linux, connect () never succeeds, and you always need to wait for write capabilities. However, for example, on FreeBSD, I saw a non-blocking connection () to the local host right after that.
Ambroz Bizjak
source share