From b2b11bb97b801680cf6673aaf11f968034614409 Mon Sep 17 00:00:00 2001 From: clowwindy Date: Sun, 18 Jan 2015 17:37:52 +0800 Subject: [PATCH] add fallback for access denied --- shadowsocks-csharp/Controller/PolipoRunner.cs | 32 ++++++++++++------- 1 file changed, 21 insertions(+), 11 deletions(-) diff --git a/shadowsocks-csharp/Controller/PolipoRunner.cs b/shadowsocks-csharp/Controller/PolipoRunner.cs index d24ad36..de63dd4 100755 --- a/shadowsocks-csharp/Controller/PolipoRunner.cs +++ b/shadowsocks-csharp/Controller/PolipoRunner.cs @@ -85,20 +85,30 @@ namespace Shadowsocks.Controller private int GetFreePort() { - IPGlobalProperties properties = IPGlobalProperties.GetIPGlobalProperties(); - IPEndPoint[] tcpEndPoints = properties.GetActiveTcpListeners(); + int defaultPort = 8123; + try + { + IPGlobalProperties properties = IPGlobalProperties.GetIPGlobalProperties(); + IPEndPoint[] tcpEndPoints = properties.GetActiveTcpListeners(); - List usedPorts = new List(); - foreach (IPEndPoint endPoint in IPGlobalProperties.GetIPGlobalProperties().GetActiveTcpListeners()) - { - usedPorts.Add(endPoint.Port); - } - for (int port = 8123; port < 65535; port++) - { - if (!usedPorts.Contains(port)) + List usedPorts = new List(); + foreach (IPEndPoint endPoint in IPGlobalProperties.GetIPGlobalProperties().GetActiveTcpListeners()) { - return port; + usedPorts.Add(endPoint.Port); } + for (int port = defaultPort; port < 65535; port++) + { + if (!usedPorts.Contains(port)) + { + return port; + } + } + } + catch (Exception e) + { + // in case access denied + Logging.LogUsefulException(e); + return defaultPort; } throw new Exception("No free port found."); }