Skip to content

Commit 5dd834e

Browse files
committed
Added limit of 255 open sockets
1 parent 1d1eae8 commit 5dd834e

File tree

3 files changed

+22
-2
lines changed

3 files changed

+22
-2
lines changed

sockets/include/CSocket.h

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,7 @@ class CSocket
4444
bool IsConnected ();
4545

4646
void* GetUserdata ();
47+
static int GetTotalOpenSocketCount ();
4748

4849
private:
4950
bool ProcessTargetLocation (const string& strHost, const unsigned short& usPort);
@@ -61,6 +62,7 @@ class CSocket
6162
struct sockaddr_in m_sSockAddr;
6263

6364
SOCKET m_pSocket;
65+
static int ms_iTotalOpenSocketCount;
6466
};
6567

6668
#endif

sockets/src/CFunctions.cpp

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,14 @@ int CFunctions::sockOpen(lua_State* luaVM)
2525
// Make sure host is a string, and port is a number
2626
if (lua_type(luaVM, 1) == LUA_TSTRING && lua_type(luaVM, 2) == LUA_TNUMBER)
2727
{
28+
29+
if ( CSocket::GetTotalOpenSocketCount () >= 255 )
30+
{
31+
pModuleManager->ErrorPrintf("[Sockets] Can't sockOpen as 255 sockets already open");
32+
lua_pushboolean(luaVM, false);
33+
return 1;
34+
}
35+
2836
// Put the host in a string, and the port in an unsigned short
2937
string strHost = lua_tostring(luaVM, 1);
3038
unsigned short usPort = static_cast < unsigned short > ( lua_tonumber ( luaVM, 2 ) );

sockets/src/CSocket.cpp

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
******************************************************/
88

99
#include "CSocket.h"
10+
int CSocket::ms_iTotalOpenSocketCount = 0;
1011

1112
CSocket::CSocket(lua_State *luaVM, const string& strHost, const unsigned short& usPort)
1213
{
@@ -29,6 +30,8 @@ CSocket::CSocket(lua_State *luaVM, const string& strHost, const unsigned short&
2930
if (m_pSocket == ERR_INVALID_SOCKET)
3031
return;
3132

33+
ms_iTotalOpenSocketCount++;
34+
3235
// Set the socket to non-blocking mode
3336
SetNonBlocking();
3437

@@ -214,9 +217,11 @@ void CSocket::CloseSocket()
214217
shutdown(m_pSocket, 1);
215218

216219
#ifdef WIN32
217-
closesocket(m_pSocket);
220+
if ( closesocket(m_pSocket) == 0 )
221+
ms_iTotalOpenSocketCount--;
218222
#else
219-
close(m_pSocket);
223+
if ( close(m_pSocket) == 0 )
224+
ms_iTotalOpenSocketCount--;
220225
#endif
221226

222227
// Unset the socket variable, so there's no mistaking there
@@ -258,3 +263,8 @@ void CSocket::TriggerEvent(const string eventName, const string arg1)
258263

259264
args.Call(m_pLuaVM, "triggerEvent");
260265
}
266+
267+
int CSocket::GetTotalOpenSocketCount()
268+
{
269+
return ms_iTotalOpenSocketCount;
270+
}

0 commit comments

Comments
 (0)