From 1e7a8de34aa6f1b4a3d3935c0ff81a50e8e228b5 Mon Sep 17 00:00:00 2001 From: Syrone Wong Date: Sat, 3 Dec 2016 00:00:31 +0800 Subject: [PATCH] Fix privoxy listening port conflict (#920) Let TCP stack find a free port for us Signed-off-by: Syrone Wong --- .../Controller/Service/PrivoxyRunner.cs | 33 ++++++---------------- 1 file changed, 9 insertions(+), 24 deletions(-) diff --git a/shadowsocks-csharp/Controller/Service/PrivoxyRunner.cs b/shadowsocks-csharp/Controller/Service/PrivoxyRunner.cs index 895b659f..1dff5add 100644 --- a/shadowsocks-csharp/Controller/Service/PrivoxyRunner.cs +++ b/shadowsocks-csharp/Controller/Service/PrivoxyRunner.cs @@ -6,6 +6,7 @@ using System.IO; using System.Linq; using System.Net; using System.Net.NetworkInformation; +using System.Net.Sockets; using System.Runtime.InteropServices; using System.Text; using System.Windows.Forms; @@ -41,17 +42,10 @@ namespace Shadowsocks.Controller } } - public int RunningPort - { - get - { - return _runningPort; - } - } + public int RunningPort => _runningPort; public void Start(Configuration configuration) { - Server server = configuration.GetCurrentServer(); if (_process == null) { Process[] existingPrivoxy = Process.GetProcessesByName("ss_privoxy"); @@ -90,6 +84,7 @@ namespace Shadowsocks.Controller if (_process != null) { KillProcess(_process); + _process.Dispose(); _process = null; } RefreshTrayArea(); @@ -160,21 +155,12 @@ namespace Shadowsocks.Controller 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 = defaultPort; port <= 65535; port++) - { - if (!usedPorts.Contains(port)) - { - return port; - } - } + // TCP stack please do me a favor + TcpListener l = new TcpListener(IPAddress.Loopback, 0); + l.Start(); + var port = ((IPEndPoint)l.LocalEndpoint).Port; + l.Stop(); + return port; } catch (Exception e) { @@ -182,7 +168,6 @@ namespace Shadowsocks.Controller Logging.LogUsefulException(e); return defaultPort; } - throw new Exception("No free port found."); } [StructLayout(LayoutKind.Sequential)]