ConnectEx returns false and WSAGetLastError returns 0

556 views Asked by At

this snippet is part of a function that should return true when a socket is connected (or connecting) or false if anything fails.

    if(bind(socket_, reinterpret_cast<sockaddr*>(&any), sizeof any) < 0)
    {
        DWORD err = GetLastError();
        logger() << "bind: " << ErrorMessage(err) << std::endl;
        return false;
    }

    rc = ConnectEx(socket_,
        reinterpret_cast<sockaddr*>(&addr_),
        sizeof addr_,
        NULL, 0, NULL,
        &connectOv_.ov);
    if(rc)
    {
        setsockopt(socket_, SOL_SOCKET, SO_UPDATE_CONNECT_CONTEXT, NULL, 0);
        return true;
    }
    DWORD err = GetLastError();
    if(err == WSA_IO_PENDING)
    {
        return true;
    } 
    logger() << "connect: " << ErrorMessage(rc) << std::endl;
    return false;

I fail to see why rc and err are always zero, no matter the actual outcome of the block. If the parameters are correct (sequence above) this block works despite the inidication of failure (I see the socket is connected with netstat). But if I tweak the parameters, by changing the overlapped to NULL or the socket to -1, the functions return the same values.

1

There are 1 answers

2
user666412 On BEST ANSWER

Missed some context in the problem description. The socket was bound to an I/O completion port. The function call failed but result of ConnectEx was received through GetQueuedCompletionStatus in a worker thread.

EDIT: I should have called WSAGetLastError() instead.