I want to create a non-blocking connect. Like this:
socket.connect(); // returns immediately
For this, I use another thread, an infinite lo
You should use the following steps for an async connect:
socket(..., SOCK_NONBLOCK, ...)
connect(fd, ...)
0
nor EINPROGRESS
, then abort with errorfd
is signalled as ready for outputgetsockopt(fd, SOL_SOCKET, SO_ERROR, ...)
No loops - unless you want to handle EINTR
.
If the client is started first, you should see the error ECONNREFUSED
in the last step. If this happens, close the socket and start from the beginning.
It is difficult to tell what's wrong with your code, without seeing more details. I suppose, that you do not abort on errors in your check_socket
operation.
D. J. Bernstein gathered together various methods how to check if an asynchronous connect()
call succeeded or not. Many of these methods do have drawbacks on certain systems, so writing portable code for that is unexpected hard. If anyone want to read all the possible methods and their drawbacks, check out this document.
For those who just want the tl;dr version, the most portable way is the following:
Once the system signals the socket as writable, first call getpeername()
to see if it connected or not. If that call succeeded, the socket connected and you can start using it. If that call fails with ENOTCONN
, the connection failed. To find out why it failed, try to read one byte from the socket read(fd, &ch, 1)
, which will fail as well but the error you get is the error you would have gotten from connect()
if it wasn't non-blocking.
There are a few ways to test if a nonblocking connect succeeds.
Ref: UNIX Network Programming V1