Linux, sockets, non-blocking connect

前端 未结 3 622
北海茫月
北海茫月 2020-12-25 14:42

I want to create a non-blocking connect. Like this:

socket.connect(); // returns immediately

For this, I use another thread, an infinite lo

3条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-25 15:18

    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.

提交回复
热议问题