Bug 34764 - TcpClient (and UdpClient) constructors leak a socket on exception
Summary: TcpClient (and UdpClient) constructors leak a socket on exception
Status: RESOLVED FIXED
Alias: None
Product: Class Libraries
Classification: Mono
Component: System ()
Version: master
Hardware: Other Other
: --- normal
Target Milestone: Untriaged
Assignee: Bugzilla
URL:
Depends on:
Blocks:
 
Reported: 2015-10-12 12:00 UTC by Steffen Kieß
Modified: 2016-10-10 14:49 UTC (History)
2 users (show)

Tags:
Is this bug a regression?: ---
Last known good build:

Notice (2018-05-24): bugzilla.xamarin.com is now in read-only mode.

Please join us on Visual Studio Developer Community and in the Xamarin and Mono organizations on GitHub to continue tracking issues. Bugzilla will remain available for reference in read-only mode. We will continue to work on open Bugzilla bugs, copy them to the new locations as needed for follow-up, and add the new items under Related Links.

Our sincere thanks to everyone who has contributed on this bug tracker over the years. Thanks also for your understanding as we make these adjustments and improvements for the future.


Please create a new report on GitHub or Developer Community with your current version information, steps to reproduce, and relevant error messages or log files if you are hitting an issue that looks similar to this resolved bug and you do not yet see a matching new report.

Related Links:
Status:
RESOLVED FIXED

Description Steffen Kieß 2015-10-12 12:00:26 UTC
Description of Problem:
Some constructors for TcpClient can leak a socket if they throw an exception after the socket has been created. In this case the caller cannot destroy the TcpClient (because the constructor threw an exception) and the socket will remain open until it is collected by the GC.


Steps to reproduce the problem:
cat > test.cs << EOF
using System;
using System.Diagnostics;
using System.Net.Sockets;
public class Test {
  public static void Main () {
    for (int i = 0; i < 2000; i++) {
      try {
        // Assuming nothing is running on port 1234
        using (var cl = new TcpClient ("127.0.0.1", 1234)) {
        //using (var cl = new TcpClient ()) {
        //  cl.Connect ("127.0.0.1", 1234);
        }
        Console.WriteLine ("Success");
      } catch (Exception e) {
        Console.WriteLine ("Error: " + e.Message);
      }
    }
    //Process.Start (new ProcessStartInfo ("sh", "-c 'ls -l /proc/$PPID/fd/'")).WaitForExit ();
  }
}
EOF
gmcs test.cs
mono test.exe | uniq -c


Actual Results:
   1021 Error: Connection refused
    979 Error: Too many open files


Expected Results:
   2000 Error: Connection refused


Probably all TcpClient and UdpClient constructors should call Close() if the constructor fails.
Comment 1 Marek Safar 2016-10-10 14:49:03 UTC
Works as expected with Mono 4.8