Merge pull request #215 from MaxXor/pr/214

UPnP fix
This commit is contained in:
MaxXor 2015-05-26 22:13:59 +02:00
commit ad7fd821af
3 changed files with 19 additions and 9 deletions

View File

@ -1,4 +1,5 @@
using System.Net;
using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using NATUPNPLib;
@ -7,11 +8,15 @@ namespace xServer.Core.Helper
{
internal static class UPnP
{
public static bool IsPortForwarded { get; private set; }
public static ushort Port { get; private set; }
public static void ForwardPort(ushort port)
{
Port = port;
new Thread(() =>
{
EndPoint endPoint;
string ipAddr = string.Empty;
int retry = 0;
@ -20,6 +25,7 @@ namespace xServer.Core.Helper
try
{
TcpClient c = null;
EndPoint endPoint;
try
{
c = new TcpClient();
@ -38,7 +44,7 @@ namespace xServer.Core.Helper
if (endPoint != null)
{
ipAddr = endPoint.ToString();
int index = ipAddr.IndexOf(":");
int index = ipAddr.IndexOf(":", StringComparison.Ordinal);
ipAddr = ipAddr.Remove(index);
// We got through successfully and with an endpoint and a parsed IP address. We may exit the loop.
@ -63,6 +69,7 @@ namespace xServer.Core.Helper
IStaticPortMappingCollection portMap = new UPnPNAT().StaticPortMappingCollection;
if (portMap != null)
portMap.Add(port, "TCP", port, ipAddr, true, "xRAT 2.0 UPnP");
IsPortForwarded = true;
}
catch
{
@ -70,13 +77,14 @@ namespace xServer.Core.Helper
}).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
{

View File

@ -179,11 +179,11 @@ namespace xServer.Forms
if (ListenServer.Listening)
ListenServer.Disconnect();
if (XMLSettings.UseUPnP)
UPnP.RemovePort(ushort.Parse(XMLSettings.ListenPort.ToString()));
if (UPnP.IsPortForwarded)
UPnP.RemovePort();
nIcon.Visible = false;
FrmMain.Instance = null;
Instance = null;
}
private void lstClients_SelectedIndexChanged(object sender, EventArgs e)

View File

@ -45,7 +45,7 @@ namespace xServer.Forms
{
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 @@ namespace xServer.Forms
try
{
_listenServer.Disconnect();
if (Core.Helper.UPnP.IsPortForwarded)
Core.Helper.UPnP.RemovePort();
}
finally
{