3 using System.Net.Sockets;
4 using System.Collections.Generic;
6 namespace MonoTests.Helpers {
8 public static class NetworkHelpers
10 static Random rndPort = new Random ();
11 static HashSet<int> portsTable = new HashSet<int> ();
13 public static int FindFreePort ()
15 return LocalEphemeralEndPoint ().Port;
18 public static IPEndPoint LocalEphemeralEndPoint ()
22 while (counter < 1000) {
23 var testingPort = rndPort.Next (10000, 60000);
25 var ep = new IPEndPoint (IPAddress.Loopback, testingPort);
28 if (portsTable.Contains (testingPort))
34 using (var socket = new Socket (ep.AddressFamily, SocketType.Stream, ProtocolType.Tcp)) {
39 portsTable.Add (testingPort);
41 } catch (SocketException) { }
45 throw new ApplicationException ($"Could not find available local port after {counter} retries");