Quasar/Server/Core/Helper/UPnP.cs

72 lines
2.2 KiB
C#
Raw Normal View History

2015-07-15 12:55:44 +00:00
using System.Collections.Generic;
2014-07-30 12:03:00 +00:00
using System.Threading;
2015-07-15 12:55:44 +00:00
using Mono.Nat;
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-07-15 12:55:44 +00:00
private static readonly HashSet<INatDevice> Devices = new HashSet<INatDevice>();
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-07-15 12:55:44 +00:00
NatUtility.DeviceFound += DeviceFound;
NatUtility.DeviceLost += DeviceLost;
NatUtility.StartDiscovery();
2015-05-26 19:55:23 +00:00
2014-07-30 12:03:00 +00:00
new Thread(() =>
{
2015-07-19 08:22:04 +00:00
int trys = 0;
while (Devices.Count == 0 && trys < 10) // wait until first device found
2014-07-30 12:03:00 +00:00
{
2015-07-19 08:22:04 +00:00
trys++;
2015-07-15 12:55:44 +00:00
Thread.Sleep(1000);
}
2015-03-18 17:12:45 +00:00
2015-07-19 08:22:04 +00:00
if (Devices.Count == 0) return;
2014-07-30 12:03:00 +00:00
try
{
2015-07-15 12:55:44 +00:00
foreach (var device in Devices)
{
2015-07-24 23:46:55 +00:00
if (device.GetSpecificMapping(Protocol.Tcp, Port).PublicPort < 0) //if port is not mapped
{
device.CreatePortMap(new Mapping(Protocol.Tcp, Port, Port));
IsPortForwarded = true;
}
}
2014-07-30 12:03:00 +00:00
}
2015-07-15 12:55:44 +00:00
catch (MappingException)
{
2015-07-15 12:55:44 +00:00
IsPortForwarded = false;
}
2014-07-30 12:03:00 +00:00
}).Start();
}
2014-07-30 14:34:42 +00:00
2015-07-15 12:55:44 +00:00
private static void DeviceFound(object sender, DeviceEventArgs args)
{
Devices.Add(args.Device);
}
private static void DeviceLost(object sender, DeviceEventArgs args)
{
Devices.Remove(args.Device);
}
2015-05-26 19:55:23 +00:00
public static void RemovePort()
2014-07-30 14:34:42 +00:00
{
2015-07-15 12:55:44 +00:00
foreach (var device in Devices)
{
2015-07-15 12:55:44 +00:00
if (device.GetSpecificMapping(Protocol.Tcp, Port).PublicPort > 0) // if port map exists
{
device.DeletePortMap(new Mapping(Protocol.Tcp, Port, Port));
2015-07-24 23:46:55 +00:00
IsPortForwarded = false;
2015-07-15 12:55:44 +00:00
}
}
2015-07-15 12:55:44 +00:00
NatUtility.StopDiscovery();
2014-07-30 14:34:42 +00:00
}
2014-07-30 12:03:00 +00:00
}
}