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