Imported Upstream version 5.8.0.22

Former-commit-id: df344e34b07851d296efb3e6604c8db42b6f7aa3
This commit is contained in:
Xamarin Public Jenkins (auto-signing)
2017-10-19 20:04:20 +00:00
parent 5f4a27cc8a
commit 7d05485754
5020 changed files with 114082 additions and 186061 deletions

View File

@@ -1,22 +1,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 ()
{
TcpListener l = new TcpListener(IPAddress.Loopback, 0);
l.Start();
int port = ((IPEndPoint)l.LocalEndpoint).Port;
l.Stop();
return port;
return LocalEphemeralEndPoint ().Port;
}
public static IPEndPoint LocalEphemeralEndPoint ()
{
return new IPEndPoint (IPAddress.Loopback, FindFreePort());
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");
}
}
}