Skip to content

Commit

Permalink
Use a use count for sockets on Windows
Browse files Browse the repository at this point in the history
In order to ensure that WSACleanup() is not called for sockets that have
never been opened, use a use count when opening and closing sockets and
call WSACleanup() only when it reaches 0.
  • Loading branch information
Colin Ward authored and hitman-codehq committed Aug 6, 2024
1 parent 061cb22 commit 84183b1
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 3 deletions.
29 changes: 26 additions & 3 deletions StdSocket.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,12 @@

#endif /* ! defined(__unix__) || defined(__amigaos__) */

#ifdef WIN32

int RSocket::m_useCount;

#endif /* WIN32 */

/**
* Typeinfo workaround.
* This is a workaround for Amiga GCC 6.5.0b. In order to catch an exception that is derived from the
Expand Down Expand Up @@ -75,7 +81,11 @@ int RSocket::open(const char *a_host, unsigned short a_port)

WSAData wsaData;

if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0)
if (WSAStartup(MAKEWORD(2, 2), &wsaData) == 0)
{
++m_useCount;
}
else
{
return KErrGeneral;
}
Expand Down Expand Up @@ -140,6 +150,13 @@ int RSocket::open(const char *a_host, unsigned short a_port)

void RSocket::close()
{

#ifdef WIN32

bool socketUsed = m_socket != INVALID_SOCKET || m_serverSocket != INVALID_SOCKET;

#endif /* WIN32 */

if (m_socket != INVALID_SOCKET)
{
closesocket(m_socket);
Expand All @@ -154,9 +171,15 @@ void RSocket::close()

#ifdef WIN32

WSACleanup();
if (socketUsed)
{
if (--m_useCount == 0)
{
DEBUGCHECK((WSACleanup() == 0), "RSocket::close() => Unable to shut down Winsock");
}
}

#endif
#endif /* WIN32 */

}

Expand Down
6 changes: 6 additions & 0 deletions StdSocket.h
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,12 @@ class RSocket

private:

#ifdef WIN32

static int m_useCount; /**< Number of times the socket has been opened */

#endif /* WIN32 */

SOCKET m_serverSocket; /**< The socket on which to listen for connections */

public:
Expand Down

0 comments on commit 84183b1

Please sign in to comment.