2015-08-26 07:17:56 -04:00
|
|
|
using System;
|
|
|
|
using System.Net;
|
|
|
|
using System.Net.Sockets;
|
2017-10-19 20:04:20 +00:00
|
|
|
using System.Collections.Generic;
|
2015-08-26 07:17:56 -04:00
|
|
|
|
|
|
|
namespace MonoTests.Helpers {
|
|
|
|
|
|
|
|
public static class NetworkHelpers
|
|
|
|
{
|
2017-10-19 20:04:20 +00:00
|
|
|
static Random rndPort = new Random ();
|
|
|
|
static HashSet<int> portsTable = new HashSet<int> ();
|
|
|
|
|
2015-08-26 07:17:56 -04:00
|
|
|
public static int FindFreePort ()
|
|
|
|
{
|
2017-10-19 20:04:20 +00:00
|
|
|
return LocalEphemeralEndPoint ().Port;
|
2015-08-26 07:17:56 -04:00
|
|
|
}
|
2017-10-19 20:04:20 +00:00
|
|
|
|
2015-08-26 07:17:56 -04:00
|
|
|
public static IPEndPoint LocalEphemeralEndPoint ()
|
|
|
|
{
|
2017-10-19 20:04:20 +00:00
|
|
|
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");
|
2015-08-26 07:17:56 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|