[Mono-dev] TcpListener.AcceptTcpClient leaks a socket at each call
"Andrés G. Aragoneses"
knocte at gmail.com
Wed Jan 22 22:15:30 UTC 2014
On 22/01/14 22:32, Jonathan Gagnon wrote:
> 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?
Propose your solution as diff format please, it's much easier to
understand and review.
More information about the Mono-devel-list
mailing list