Search code examples
c++tcplistenerwinsock

Winsock TCP listener stays in LISTENING state after successful closesocket() call


I'm working on an existing DLL where a TCP listening socket is created and is set to immediately rebind to the same socket using SO_REUSEADDR in case of failure. Currently, however, there's an issue in which the listener will stay in LISTENING state, even after a successful call to closesocket(); since it doesn't enter TIME_WAIT, a new listener is created on the same port when the socket is recreated. Clients then fail to connect to the new listener (presumably). SO_LINGER is set to 0 seconds. There are no pending transmissions when the socket is closed. The oldest socket seems to close after about ten seconds without visibly entering another state.

What could keep a listener in LISTENING state after a successful call to closesocket()?


Solution

    1. You closed the wrong socket.
    2. You duplicated the handle and forgot to close the duplicate.
    3. Somebody else snapped up the port.
    4. Your failure code detects failure of the listener when something else is what failed.
    5. Your listener is reporting failure when it didn't fail.
    6. Your failure mode corrupts the state so closesocket() closes something else.