26

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

socket.connect(); // returns immediately

For this, I use another thread, an infinite loop and Linux epoll. Like this(pseudocode):

// in another thread
{
  create_non_block_socket();
  connect();

  epoll_create();
  epoll_ctl(); // subscribe socket to all events
  while (true)
  {
    epoll_wait(); // wait a small time(~100 ms)
    check_socket(); // check on EPOLLOUT event
  }
}

If I run a server and then a client, all it works. If I first run a client, wait a some small time, run a server, then the client doesn't connect.

What am I doing wrong? Maybe it can be done differently?

3
  • If you are raising another thread to perform the connect, why are you doing it asynchronous? Also, may as well put the rest of the comms in there. Jul 21, 2013 at 8:27
  • Well, how to do it without epoll and nonblocking? If I just call connect() then it will block and wait for connect(am I right?). But then if I want to join this connecting thread to main thread, I can't to do it, because connecting thread will in blocking state. Sorry if I am wrong.
    – herolover
    Jul 21, 2013 at 8:38
  • 1
    This is not 'async'. This is non-blocking.
    – user207421
    Jul 21, 2013 at 9:52

3 Answers 3

55

You should use the following steps for an async connect:

  • create socket with socket(..., SOCK_NONBLOCK, ...)
  • start connection with connect(fd, ...)
  • if return value is neither 0 nor EINPROGRESS, then abort with error
  • wait until fd is signalled as ready for output
  • check status of socket with getsockopt(fd, SOL_SOCKET, SO_ERROR, ...)
  • done

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.

13
  • I know this is an old comment, but I just wanted to note that I had to wait for read in order to catch ETIMEDOUT. This occurred when the SYN response was not returned. If I only waited for write then the socket would disappear from netstat (from SYN_SENT state) but I'd get no notification that the socket was writable to call getsockopt and find ETIMEDOUT. I also added a call immediately after connect to getsockopt to see if there were any immediate errors available before polling. Jun 10, 2015 at 15:02
  • 1
    @DreamWarrior: That's weird. Take a look at connect(2) and connect(3) and search for poll. Both man pages state, that you should wait for indication, that the socket is writable. Can you prodive a minimal example, that shows the unexpected behavior?
    – nosid
    Jun 11, 2015 at 20:02
  • 1
    @DreamWarrior: I can't reproduce the problem you have described. I have written a minimal test program, and it correctly reports ETIMEDOUT using POLLOUT.
    – nosid
    Jun 19, 2015 at 18:57
  • 1
    This is not an 'async connect'.This is a non-blocking connect. Given that the program is doing exactly nothing except waiting for success or failure, the approach is completey futile. It would be more to the point to do the connect in blocking mode and then revert to non-blocking for whatever follows, if anything.
    – user207421
    Jul 15, 2018 at 9:57
  • 6
    When getsockopt(fd, SOL_SOCKET, SO_ERROR, ...) returns 0, with 0 in so_error, this does not mean that the socket is connected. This means no error occured until now. In this specific case, you need to call getpeername() and if getpeername() returns 0, this means the socket is connected. If the socket is not connected, getpeername() returns -1 with ENOTCONN in errno. getsockopt(fd, SOL_SOCKET, SO_ERROR, ...) can inform you about a connection refused, but not about a connected socket. You need to use getpeername() or other means to be sure the socket is connected. Dec 12, 2018 at 19:49
9

There are a few ways to test if a nonblocking connect succeeds.

  1. call getpeername() first, if it failed with error ENOTCONN, the connection failed. then call getsockopt with SO_ERROR to get the pending error on the socket
  2. call read with a length of 0. if the read failed, the connection failed, and the errno for read indicates why the connection failed; read returns 0 if connection succeeds
  3. call connect again; if the errno is EISCONN, the connection is already connected and the first connect succeeded.

Ref: UNIX Network Programming V1

1
  • Please, note: the read() man page says: "If count is zero, read() may detect the errors described below. In the absence of any errors, or if read() does not check for errors, a read() with a count of 0 returns zero and has no other effects." So, it MAY detect the errors.
    – VL-80
    Aug 23, 2021 at 1:12
3

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.