[Mono-dev] TcpListener.AcceptTcpClient leaks a socket at each call

Jonathan Gagnon jonathan.gagnon at croesus.com
Wed Jan 22 21:32:12 UTC 2014


I found a leak in TcpListener.AcceptTcpClient :

public TcpClient AcceptTcpClient ()
{
if (!active)
 throw new InvalidOperationException ("Socket is not listening");

Socket clientSocket = server.Accept ();

TcpClient client = new TcpClient();  // this call creates a socket even
though we don't need it
// use internal method SetTcpClient to make a
 // client with the specified socket
client.SetTcpClient (clientSocket);  // This method leaks the socket
created by the default constructor.

return client;
}


The method calls the default TcpClient constructor which creates a new
socket.  SetTcpClient is then called to assign the accepted socket to the
TcpClient object.  The problem is that the SetTcpClient simply replaces the
old socket reference by the new without closing the old socket.  The result
is that the socket created by the default constructor remains until the GC
reclaims it.

The fix would be really easy.  Instead of calling the default TcpClient
constructor, a new constructor could be created taking the socket as
parameter.  We would then avoid creating and leaking a socket every time
the method is called.  The fixed method would look like this :

public TcpClient AcceptTcpClient ()
{
if (!active)
throw new InvalidOperationException ("Socket is not listening");

Socket clientSocket = server.Accept ();

TcpClient client = new TcpClient(clientSocket);

return client;
}


I could create a fix with the proposed solution.  Any thoughts?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.ximian.com/pipermail/mono-devel-list/attachments/20140122/0a797043/attachment.html>


More information about the Mono-devel-list mailing list