I want to create a non-blocking connect. Like this:
socket.connect(); // returns immediately
For this, I use another thread, an infinite lo
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.