Hi all:

According to the library, recv() will return a zero if the socket is closed, and a SOCKET_ERROR if the socket meets an error.
But when I closed my socket (at least I think I closed it properly), recv() returned a SOCKET_ERROR other than zero. Wondering why?

Thank you whoever help me in advance.

Dani AI

Generated

A few practical diagnostics and fixes that address what hit and clarify 's tip.

First, check the Winsock error code immediately after recv fails — use WSAGetLastError() (Winsock error codes), not GetLastError(). That difference matters because Winsock reports its own codes (for example, a peer reset shows up as WSAECONNRESET, nonblocking sockets report WSAEWOULDBLOCK, etc.). Call WSAGetLastError() before any other Winsock/Win32 calls so the value is reliable.

A minimal pattern:

int n = recv(s, buf, len, 0);
if (n == SOCKET_ERROR) {
    int err = WSAGetLastError();
    // log err and handle cases: WSAECONNRESET, WSAEWOULDBLOCK, WSAENOTCONN, WSAESHUTDOWN, ...
}

Common causes to consider

  • The peer aborted (RST) instead of a graceful close (FIN): this produces a Winsock error such as WSAECONNRESET rather than a normal EOF. SO_LINGER settings or an immediate closesocket with linger can force an abortive close.
  • Nonblocking mode: WSAEWOULDBLOCK simply means "try again later"; use select/WSAPoll or handle it accordingly.
  • Local code race: calling closesocket (or using the socket from multiple threads) while another thread is in recv can produce errors; set the socket variable to INVALID_SOCKET after closing and coordinate shutdown with shutdown().

Useful references: the Winsock recv behavior and error list, WSAGetLastError, and the SO_LINGER option in the Microsoft docs. These will help correlate the exact error code you see with network traces (Wireshark) and your socket lifecycle (shutdown vs close).

Recommended Answers

All 2 Replies

Hi all:

According to the library, recv() will return a zero if the socket is closed, and a SOCKET_ERROR if the socket meets an error.
But when I closed my socket (at least I think I closed it properly), recv() returned a SOCKET_ERROR other than zero. Wondering why?

Thank you whoever help me in advance.

Now will be a good time to use the GetLastError() function.

Thanks Wolf.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.