Merge pull request #5589 from marek-safar/tests
[mono.git] / mcs / class / test-helpers / NetworkHelpers.cs
1 using System;
2 using System.Net;
3 using System.Net.Sockets;
4 using System.Collections.Generic;
5
6 namespace MonoTests.Helpers {
7
8         public static class NetworkHelpers
9         {
10                 static Random rndPort = new Random ();
11                 static HashSet<int> portsTable = new HashSet<int> ();
12
13                 public static int FindFreePort ()
14                 {
15                         return LocalEphemeralEndPoint ().Port;
16                 }
17
18                 public static IPEndPoint LocalEphemeralEndPoint ()
19                 {
20                         int counter = 0;
21
22                         while (counter < 1000) {
23                                 var testingPort = rndPort.Next (10000, 60000);
24
25                                 var ep = new IPEndPoint (IPAddress.Loopback, testingPort);
26
27                                 lock (portsTable) {
28                                         if (portsTable.Contains (testingPort))
29                                                 continue;
30
31                                         ++counter;
32
33                                         try {
34                                                 using (var socket = new Socket (ep.AddressFamily, SocketType.Stream, ProtocolType.Tcp)) {
35                                                         socket.Bind (ep);
36                                                         socket.Close ();
37                                                 }
38
39                                                 portsTable.Add (testingPort);
40                                                 return ep;
41                                         } catch (SocketException) { }
42                                 }
43                         }
44
45                         throw new ApplicationException ($"Could not find available local port after {counter} retries");
46                 }
47         }
48 }