From 7e13fa080ed04aa627746fff98e20a5864d18f62 Mon Sep 17 00:00:00 2001 From: d3agle Date: Tue, 26 May 2015 14:55:23 -0500 Subject: [PATCH] small behavior fix #213 update --- Server/Core/Helper/UPnP.cs | 27 +++++++++++++++++++++++++-- Server/Forms/FrmMain.cs | 2 +- Server/Forms/FrmSettings.cs | 4 +++- 3 files changed, 29 insertions(+), 4 deletions(-) diff --git a/Server/Core/Helper/UPnP.cs b/Server/Core/Helper/UPnP.cs index 583f8942..fca537a3 100644 --- a/Server/Core/Helper/UPnP.cs +++ b/Server/Core/Helper/UPnP.cs @@ -7,8 +7,28 @@ namespace xServer.Core.Helper { internal static class UPnP { + private static bool _isPortForwarded = false; + public static bool IsPortForwarded + { + get + { + return _isPortForwarded; + } + } + + private static ushort _port; + public static ushort Port + { + get + { + return _port; + } + } + public static void ForwardPort(ushort port) { + _port = port; + new Thread(() => { EndPoint endPoint; @@ -63,20 +83,23 @@ public static void ForwardPort(ushort port) IStaticPortMappingCollection portMap = new UPnPNAT().StaticPortMappingCollection; if (portMap != null) portMap.Add(port, "TCP", port, ipAddr, true, "xRAT 2.0 UPnP"); + _isPortForwarded = true; } catch { + } }).Start(); } - public static void RemovePort(ushort port) + public static void RemovePort() { try { IStaticPortMappingCollection portMap = new UPnPNAT().StaticPortMappingCollection; if (portMap != null) - portMap.Remove(port, "TCP"); + portMap.Remove(_port, "TCP"); + _isPortForwarded = false; } catch { diff --git a/Server/Forms/FrmMain.cs b/Server/Forms/FrmMain.cs index 0198126f..e8317dfe 100644 --- a/Server/Forms/FrmMain.cs +++ b/Server/Forms/FrmMain.cs @@ -179,7 +179,7 @@ private void FrmMain_FormClosing(object sender, FormClosingEventArgs e) if (ListenServer.Listening) ListenServer.Disconnect(); - if (XMLSettings.UseUPnP && ListenServer.Listening) + if (UPnP.IsPortForwarded) UPnP.RemovePort(ushort.Parse(XMLSettings.ListenPort.ToString())); nIcon.Visible = false; diff --git a/Server/Forms/FrmSettings.cs b/Server/Forms/FrmSettings.cs index 606ed42e..39230cca 100644 --- a/Server/Forms/FrmSettings.cs +++ b/Server/Forms/FrmSettings.cs @@ -45,7 +45,7 @@ private void btnListen_Click(object sender, EventArgs e) { try { - if (chkUseUpnp.Checked) + if (chkUseUpnp.Checked && !Core.Helper.UPnP.IsPortForwarded) Core.Helper.UPnP.ForwardPort(ushort.Parse(ncPort.Value.ToString(CultureInfo.InvariantCulture))); if(chkNoIPIntegration.Checked) NoIpUpdater.Start(); @@ -63,6 +63,8 @@ private void btnListen_Click(object sender, EventArgs e) try { _listenServer.Disconnect(); + if (Core.Helper.UPnP.IsPortForwarded) + Core.Helper.UPnP.RemovePort(); } finally {