Quasar/Server/Core/Helper/UPnP.cs

94 lines
2.9 KiB
C#
Raw Normal View History

2015-05-26 20:13:11 +00:00
using System;
using System.Net;
2014-07-30 13:08:03 +00:00
using System.Net.Sockets;
2014-07-30 12:03:00 +00:00
using System.Threading;
2015-01-13 18:29:11 +00:00
using NATUPNPLib;
2014-07-30 12:03:00 +00:00
2015-01-13 18:29:11 +00:00
namespace xServer.Core.Helper
2014-07-30 12:03:00 +00:00
{
internal static class UPnP
2014-07-30 12:03:00 +00:00
{
2015-05-26 20:13:11 +00:00
public static bool IsPortForwarded { get; private set; }
public static ushort Port { get; private set; }
2015-05-26 19:55:23 +00:00
2014-07-30 12:03:00 +00:00
public static void ForwardPort(ushort port)
{
2015-05-26 20:13:11 +00:00
Port = port;
2015-05-26 19:55:23 +00:00
2014-07-30 12:03:00 +00:00
new Thread(() =>
{
string ipAddr = string.Empty;
int retry = 0;
2014-07-30 12:03:00 +00:00
do
2014-07-30 12:03:00 +00:00
{
try
{
TcpClient c = null;
2015-05-26 20:13:11 +00:00
EndPoint endPoint;
try
{
c = new TcpClient();
c.Connect("www.google.com", 80);
endPoint = c.Client.LocalEndPoint;
}
finally
{
// Placed in here to make sure that a failed TcpClient will never linger!
2015-03-18 17:12:45 +00:00
if (c != null)
{
c.Close();
}
}
2014-07-30 12:03:00 +00:00
if (endPoint != null)
{
ipAddr = endPoint.ToString();
2015-05-26 20:13:11 +00:00
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.
break;
}
else
{
retry++;
}
}
catch
2014-07-30 12:03:00 +00:00
{
retry++;
2014-07-30 12:03:00 +00:00
}
} while (retry < 5);
2014-07-30 12:03:00 +00:00
2015-03-18 17:12:45 +00:00
if (string.IsNullOrEmpty(ipAddr)) // If we can't successfully connect
return;
2014-07-30 12:03:00 +00:00
try
{
2014-07-30 14:34:42 +00:00
IStaticPortMappingCollection portMap = new UPnPNAT().StaticPortMappingCollection;
if (portMap != null)
portMap.Add(port, "TCP", port, ipAddr, true, "xRAT 2.0 UPnP");
2015-05-26 20:13:11 +00:00
IsPortForwarded = true;
2014-07-30 12:03:00 +00:00
}
2014-07-30 14:34:42 +00:00
catch
{
}
2014-07-30 12:03:00 +00:00
}).Start();
}
2014-07-30 14:34:42 +00:00
2015-05-26 19:55:23 +00:00
public static void RemovePort()
2014-07-30 14:34:42 +00:00
{
try
{
IStaticPortMappingCollection portMap = new UPnPNAT().StaticPortMappingCollection;
if (portMap != null)
2015-05-26 20:13:11 +00:00
portMap.Remove(Port, "TCP");
IsPortForwarded = false;
2014-07-30 14:34:42 +00:00
}
catch
{
}
2014-07-30 14:34:42 +00:00
}
2014-07-30 12:03:00 +00:00
}
}