Permalink
Browse files

Ensure random port is not in use

  • Loading branch information...
1 parent 6ddd1fd commit e2b08bcffcd81b1311169701503bf1e9b0d87f5c @cscrosati cscrosati committed Dec 2, 2011
Showing with 50 additions and 4 deletions.
  1. +25 −2 Kudu.Core/SourceControl/Hg/HgServer.cs
  2. +25 −2 Kudu.SiteManagement/SiteManager.cs
@@ -4,6 +4,7 @@
using System.Threading;
using Kudu.Core.Infrastructure;
using Mercurial;
+using System.Net.NetworkInformation;
namespace Kudu.Core.SourceControl.Hg
{
@@ -181,10 +182,32 @@ public void Stop()
return null;
}
+ //TODO this is duplicated in SiteManager.cs.
private int GetRandomPort()
{
- // TODO: Ensure the port is unused
- return new Random((int)DateTime.Now.Ticks).Next(1025, 65535);
+ Random rnd = new Random((int)DateTime.Now.Ticks);
+ int randomPort = rnd.Next(1025, 65535);
+ while (!IsAvailable(randomPort))
+ {
+ randomPort = rnd.Next(1025, 65535);
+ }
+
+ return randomPort;
+ }
+
+ //TODO this is duplicated in SiteManager.cs.
+ private bool IsAvailable(int port)
+ {
+ var tcpConnections = IPGlobalProperties.GetIPGlobalProperties().GetActiveTcpConnections();
+ foreach (var connectionInfo in tcpConnections)
+ {
+ if (connectionInfo.LocalEndPoint.Port == port)
+ {
+ return false;
+ }
+ }
+
+ return true;
}
}
}
@@ -3,6 +3,7 @@
using System.Threading;
using Kudu.Core.Infrastructure;
using IIS = Microsoft.Web.Administration;
+using System.Net.NetworkInformation;
namespace Kudu.SiteManagement
{
@@ -159,10 +160,32 @@ private static IIS.ApplicationPool EnsureKuduAppPool(IIS.ServerManager iis)
return kuduAppPool;
}
+ //TODO this is duplicated in HgServer.cs.
private int GetRandomPort()
{
- // TODO: Ensure the port is unused
- return new Random((int)DateTime.Now.Ticks).Next(1025, 65535);
+ Random rnd = new Random((int) DateTime.Now.Ticks);
+ int randomPort = rnd.Next(1025, 65535);
+ while (!IsAvailable(randomPort))
+ {
+ randomPort = rnd.Next(1025, 65535);
+ }
+
+ return randomPort;
+ }
+
+ //TODO this is duplicated in HgServer.cs.
+ private bool IsAvailable(int port)
+ {
+ var tcpConnections = IPGlobalProperties.GetIPGlobalProperties().GetActiveTcpConnections();
+ foreach (var connectionInfo in tcpConnections)
+ {
+ if (connectionInfo.LocalEndPoint.Port == port)
+ {
+ return false;
+ }
+ }
+
+ return true;
}
private int CreateSite(IIS.ServerManager iis, string siteName, string siteRoot)

0 comments on commit e2b08bc

Please sign in to comment.