public IEnumerable <Mapping> GetAllMappings()
        {
            var mappingsTask = _device.GetAllMappingsAsync();

            mappingsTask.Wait();
            return(mappingsTask.Result);
        }
Example #2
0
        async Task unMapPorts()
        {
            SystemLog.addEntry("Cleaning up UPnP mappings...");
            try
            {
                if (device == null)
                {
                    initUPnP();
                }
                externalIPFromUPnP = await device.GetExternalIPAsync();

                foreach (Mapping z in await device.GetAllMappingsAsync())
                {
                    if (z.Description == Environment.MachineName + " Dimension Mapping")
                    {
                        await device.DeletePortMapAsync(z);

                        SystemLog.addEntry("Successfully deleted UPnP mapping " + z.Description);
                        UPnPActive = true;
                    }
                }
            }
            catch
            {
                UPnPActive = false;
                SystemLog.addEntry("Failed to delete UPnP mapping.");
                //UPnP probably not supported
            }
        }
Example #3
0
    private static Task Test()
    {
        var nat = new NatDiscoverer();
        var cts = new CancellationTokenSource();

        cts.CancelAfter(5000);

        NatDevice device = null;
        var       sb     = new StringBuilder();
        IPAddress ip     = null;

        return(nat.DiscoverDeviceAsync(PortMapper.Upnp, cts)
               .ContinueWith(task =>
        {
            device = task.Result;
            return device.GetExternalIPAsync();
        })
               .Unwrap()
               .ContinueWith(task =>
        {
            ip = task.Result;
            sb.AppendFormat("\nYour IP: {0}", ip);
            return device.CreatePortMapAsync(new Mapping(Protocol.Tcp, 7777, 7777, 0, "myGame Server (TCP)"));
        })
               .Unwrap()
               .ContinueWith(task =>
        {
            return device.CreatePortMapAsync(new Mapping(Protocol.Udp, 7777, 7777, 0, "myGame Server (UDP)"));
        })
               .Unwrap()
               .ContinueWith(task =>
        {
            sb.AppendFormat("\nAdded mapping: {0}:7777 -> 127.0.0.1:7777\n", ip);
            sb.AppendFormat("\n+------+-------------------------------+--------------------------------+------------------------------------+-------------------------+");
            sb.AppendFormat("\n| PORT | PUBLIC (Reacheable)           | PRIVATE (Your computer)        | Description                        |                         |");
            sb.AppendFormat("\n+------+----------------------+--------+-----------------------+--------+------------------------------------+-------------------------+");
            sb.AppendFormat("\n|      | IP Address           | Port   | IP Address            | Port   |                                    | Expires                 |");
            sb.AppendFormat("\n+------+----------------------+--------+-----------------------+--------+------------------------------------+-------------------------+");
            return device.GetAllMappingsAsync();
        })
               .Unwrap()
               .ContinueWith(task =>
        {
            foreach (var mapping in task.Result)
            {
                sb.AppendFormat("\n|  {5} | {0,-20} | {1,6} | {2,-21} | {3,6} | {4,-35}|{6,25}|",
                                ip, mapping.PublicPort, mapping.PrivateIP, mapping.PrivatePort, mapping.Description,
                                mapping.Protocol == Protocol.Tcp ? "TCP" : "UDP", mapping.Expiration.ToLocalTime());
            }
            sb.AppendFormat("\n+------+----------------------+--------+-----------------------+--------+------------------------------------+-------------------------+");
            sb.AppendFormat("\n[Removing TCP mapping] {0}:7777 -> 127.0.0.1:7777", ip);
            return device.DeletePortMapAsync(new Mapping(Protocol.Tcp, 1600, 1700));
        })
               .Unwrap()
               .ContinueWith(task =>
        {
            sb.AppendFormat("\n[Done]");
            Debug.Log(sb);
        }));
    }
Example #4
0
        public async Task <List <MyNatMapping> > GetAllMappings()
        {
            if (!m_deviceAvailable.Value)
            {
                throw new NatDeviceNotFoundException();
            }

            IEnumerable <Mapping> mappings;

            try
            { mappings = await m_device.GetAllMappingsAsync(); }
            catch (NatDeviceNotFoundException e)
            { m_deviceAvailable.Value = false; throw e; }

            if (mappings == null)
            {
                return(new List <MyNatMapping>());
            }

            List <MyNatMapping> newMappings = new List <MyNatMapping>();

            foreach (var map in mappings)
            {
                newMappings.Add(new MyNatMapping(map));
            }

            return(newMappings);
        }
Example #5
0
 private Mapping GetPublicPortMappingInternal(int public_port)
 {
     if (acquireRouterDevice() == true)
     {
         try
         {
             Task <IEnumerable <Mapping> > mappings = routerDevice.GetAllMappingsAsync();
             if (mappings.Wait(5000) == true)
             {
                 foreach (Mapping m in mappings.Result)
                 {
                     if (m.PublicPort == public_port)
                     {
                         return(m);
                     }
                 }
             }
         }
         catch (MappingException ex)
         {
             Logging.warn(String.Format("Error while obtaining current port mapping: {0}", ex.Message));
         }
     }
     return(null);
 }
Example #6
0
        public async Task <int> OpenPort()
        {
            discoverer = new NatDiscoverer();
            Random random = new Random();

            try
            {
                var cts = new CancellationTokenSource(10000);
                router = await discoverer.DiscoverDeviceAsync(PortMapper.Upnp, cts);
            }
            catch (NatDeviceNotFoundException ex)
            {
            }
            try
            {
                if (router == null)
                {
                    var cts = new CancellationTokenSource(10000);
                    router = await discoverer.DiscoverDeviceAsync(PortMapper.Pmp, cts);
                }
            }
            catch (NatDeviceNotFoundException ex)
            {
                Debug.Fail("Error: Enable port mapping on your router", ex.Message);
                return(random.Next(4000, 6000));
            }

            //Занятые udp порты
            List <int> busyUdpPorts = new List <int>();

            //Нахождение всех занятых портов (публичных и приватных)
            var mappings = await router.GetAllMappingsAsync();

            foreach (var mapping in mappings)
            {
                if (mapping.Protocol == Protocol.Udp)
                {
                    Debug.WriteLine(mapping);
                    busyUdpPorts.Add(mapping.PrivatePort);
                    busyUdpPorts.Add(mapping.PublicPort);
                }
            }

            //Нахождение свободного порта
            int availablePort = random.Next(30000, 65535);

            while (busyUdpPorts.Contains(availablePort))
            {
                availablePort = random.Next(30000, 65535);
            }

            await router.CreatePortMapAsync(new Mapping(Protocol.Udp, availablePort, availablePort, "P2P_Chat_User"));

            return(availablePort);
        }
Example #7
0
    public static Task PortForward()
    {
        var nat = new NatDiscoverer();
        var cts = new System.Threading.CancellationTokenSource();

        cts.CancelAfter(5000);

        NatDevice device = null;
        var       sb     = new StringBuilder();
        IPAddress ip     = null;

        return(nat.DiscoverDeviceAsync(PortMapper.Upnp, cts)
               .ContinueWith(task =>
        {
            device = task.Result;
            return device.GetExternalIPAsync();
        })
               .Unwrap()
               .ContinueWith(task =>
        {
            ip = task.Result;
            sb.AppendFormat("\nYour external IP: {0}", ip);
            return device.CreatePortMapAsync(new Mapping(Protocol.Tcp, UnityEngine.Networking.NetworkManager.singleton.networkPort, UnityEngine.Networking.NetworkManager.singleton.networkPort, 0, "Game Server (TCP)"));
        })
               .Unwrap()
               .ContinueWith(task =>
        {
            return device.CreatePortMapAsync(new Mapping(Protocol.Udp, UnityEngine.Networking.NetworkManager.singleton.networkPort, UnityEngine.Networking.NetworkManager.singleton.networkPort, 0, "Game Server (UDP)"));
        })
               .Unwrap()
               .ContinueWith(task =>
        {
            sb.AppendFormat("\nAdded mapping: {0}:{1} -> localIP:{1}\n", ip, UnityEngine.Networking.NetworkManager.singleton.networkPort);
            sb.AppendFormat("\n+------+-------------------------------+--------------------------------+------------------------------------+-------------------------+");
            sb.AppendFormat("\n| PROT | PUBLIC (Reacheable)           | PRIVATE (Your computer)        | Description                        |                         |");
            sb.AppendFormat("\n+------+----------------------+--------+-----------------------+--------+------------------------------------+-------------------------+");
            sb.AppendFormat("\n|      | IP Address           | Port   | IP Address            | Port   |                                    | Expires                 |");
            sb.AppendFormat("\n+------+----------------------+--------+-----------------------+--------+------------------------------------+-------------------------+");
            return device.GetAllMappingsAsync();
        })
               .Unwrap()
               .ContinueWith(task =>
        {
            foreach (var mapping in task.Result)
            {
                sb.AppendFormat("\n|  {5} | {0,-20} | {1,6} | {2,-21} | {3,6} | {4,-35}|{6,25}|",
                                ip, mapping.PublicPort, mapping.PrivateIP, mapping.PrivatePort, mapping.Description,
                                mapping.Protocol == Protocol.Tcp ? "TCP" : "UDP", mapping.Expiration.ToLocalTime());
            }
            sb.AppendFormat("\n+------+----------------------+--------+-----------------------+--------+------------------------------------+-------------------------+");
            sb.AppendFormat("\n[Done]");
            Debug.Log(sb.ToString());
        }));
    }
Example #8
0
        public async Task <bool> EnsureMapping()
        {
            NodeServerTrace.Information("EnsureMapping");

            var device = await GetNatDeviceAsync();

            return(device == null ? false : await device.GetSpecificMappingAsync(Protocol.Tcp, _ServerPort).ContinueWith(t =>
            {
                if (t.IsFaulted)
                {
                    NodeServerTrace.Error("GetExternalIP", t.Exception);
                    return false;
                }

                var mapping = t.Result;

                try
                {
                    if (mapping != null && !mapping.PrivateIP.Equals(InternalIPAddress))
                    {
                        NodeServerTrace.Information($"existing mapping mismatch. got: {mapping.PrivateIP}, need: {InternalIPAddress}");

                        _NatDevice.DeletePortMapAsync(mapping).Wait();
                        mapping = null;
                    }

                    if (mapping == null)
                    {
                        NodeServerTrace.Information($"creaing mapping with IP: {InternalIPAddress}");

                        _NatDevice.CreatePortMapAsync(
                            new Mapping(
                                Protocol.Tcp,
                                InternalIPAddress,
                                _ServerPort,
                                _ServerPort,
                                0,                                 //TODO: session lifetime?
                                MAPPING_DESC
                                )
                            ).Wait();
                    }

                    IEnumerable <Mapping> exisingMappings = _NatDevice.GetAllMappingsAsync().Result;

                    return exisingMappings.Count(exisintMapping => exisintMapping.PublicPort == _ServerPort) == 1;
                }
                catch (Exception e)
                {
                    NodeServerTrace.Error("Mapping", e);
                    return false;
                }
            }));
        }
Example #9
0
 public Task <PortResult> CheckPort(UPnPPort port)
 {
     return(Task.Run(async() =>
     {
         if (State == UPnPSupportState.NoPrepared)
         {
             return PortResult.EngineNotPrepared;
         }
         else if (State == UPnPSupportState.NotSupported)
         {
             return PortResult.EngineNotSupported;
         }
         else
         {
             try
             {
                 IEnumerable <Mapping> mappings = await device.GetAllMappingsAsync();
                 foreach (Mapping map in mappings)
                 {
                     if (map.PublicPort == port.ExternalPort)
                     {
                         if (port.Type == PortType.BOTH)
                         {
                             return PortResult.Opened;
                         }
                         else if (port.Type == PortType.TCP && map.Protocol == Protocol.Tcp)
                         {
                             return PortResult.Opened;
                         }
                         else if (port.Type == PortType.UDP && map.Protocol == Protocol.Udp)
                         {
                             return PortResult.Opened;
                         }
                         else
                         {
                             return PortResult.Closed;
                         }
                     }
                 }
                 return PortResult.Closed;
             }
             catch (Exception)
             {
                 return PortResult.FailedUnknown;
             }
         }
     }));
 }
        public async Task <IEnumerable <Mapping> > Mappings()
        {
            await GetDevice();

            return(await device.GetAllMappingsAsync());
        }
 public static async Task <IEnumerable <Mapping> > GetOpenPorts()
 {
     return(await device.GetAllMappingsAsync());
 }
Example #12
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="cancelTime">Cancellation time in milliseconds</param>
        /// <returns></returns>
        private async Task ForwardPort(int internalPort, int externalPort, int cancelTime, Protocol protocol = Protocol.Udp)
        {
            var nat = new NatDiscoverer();
            var cts = new CancellationTokenSource();

            cts.CancelAfter(cancelTime);

            NatDevice device = null;
            var       sb     = new StringBuilder();
            IPAddress ip     = null;

            await nat.DiscoverDeviceAsync(PortMapper.Upnp | PortMapper.Pmp, cts)
            .ContinueWith(task =>
            {
                device = task.Result;
                return(device.GetExternalIPAsync());
            })
            .Unwrap()
            .ContinueWith(task =>
            {
                ip      = task.Result;
                this.ip = ip;

                sb.AppendFormat("\nYour IP: {0}", ip);
                this.mapping = new Mapping(Protocol.Udp, internalPort, externalPort, lifeTime, "Game Server (Udp)");

                return(device.CreatePortMapAsync(mapping));
            })
            .Unwrap()
            .ContinueWith(task =>
            {
                sb.AppendFormat("\nAdded mapping: {0}:{1} -> 127.0.0.1:{2}\n", ip, externalPort, internalPort);
                sb.AppendFormat("\n+------+-------------------------------+--------------------------------+------------------------------------+-------------------------+");
                sb.AppendFormat("\n| PORT | PUBLIC (Reacheable)   | PRIVATE (Your computer)  | Description      |       |");
                sb.AppendFormat("\n+------+----------------------+--------+-----------------------+--------+------------------------------------+-------------------------+");
                sb.AppendFormat("\n|  | IP Address   | Port | IP Address   | Port |         | Expires     |");
                sb.AppendFormat("\n+------+----------------------+--------+-----------------------+--------+------------------------------------+-------------------------+");
                return(device.GetAllMappingsAsync());
            })
            .Unwrap()
            .ContinueWith(task =>
            {
                foreach (var mapping in task.Result)
                {
                    sb.AppendFormat("\n| {5} | {0,-20} | {1,6} | {2,-21} | {3,6} | {4,-35}|{6,25}|",
                                    ip, mapping.PublicPort, mapping.PrivateIP, mapping.PrivatePort, mapping.Description,
                                    mapping.Protocol == Protocol.Tcp ? "TCP" : "UDP", mapping.Expiration.ToLocalTime());
                }

                sb.AppendFormat("\n+------+----------------------+--------+-----------------------+--------+------------------------------------+-------------------------+");

                Found = true;

                sb.AppendFormat("\n[Done]");

                if (logAll)
                {
                    Debug.Log(sb.ToString());
                }

                return(device.GetAllMappingsAsync());
            })
            .Unwrap()
            .ContinueWith(task =>
            {
            });
        }
Example #13
0
        public static void Main(string[] args)
        {
            var nat = new NatDiscoverer();
            var cts = new CancellationTokenSource();

            cts.CancelAfter(5000);

            NatDevice device = null;
            var       sb     = new StringBuilder();
            IPAddress ip     = null;
            var       t      = nat.DiscoverDeviceAsync(PortMapper.Pmp, cts);

            t.ContinueWith(tt =>
            {
                device = tt.Result;
                device.GetExternalIPAsync()
                .ContinueWith(task =>
                {
                    ip = task.Result;
                    sb.AppendFormat("\nYour IP: {0}", ip);
                    return(device.CreatePortMapAsync(new Mapping(Protocol.Tcp, 1600, 1700, "Open.Nat (temporary)")));
                })
                .Unwrap()
                .ContinueWith(task =>
                {
                    return(device.CreatePortMapAsync(
                               new Mapping(Protocol.Tcp, 1601, 1701, "Open.Nat (Session lifetime)")));
                })
                .Unwrap()
                .ContinueWith(task =>
                {
                    return(device.CreatePortMapAsync(
                               new Mapping(Protocol.Tcp, 1602, 1702, 0, "Open.Nat (Permanent lifetime)")));
                })
                .Unwrap()
                .ContinueWith(task =>
                {
                    return(device.CreatePortMapAsync(
                               new Mapping(Protocol.Tcp, 1603, 1703, 20, "Open.Nat (Manual lifetime)")));
                })
                .Unwrap()
                .ContinueWith(task =>
                {
                    sb.AppendFormat("\nAdded mapping: {0}:1700 -> 127.0.0.1:1600\n", ip);
                    sb.AppendFormat(
                        "\n+------+-------------------------------+--------------------------------+------------------------------------+-------------------------+");
                    sb.AppendFormat("\n| PROT | PUBLIC (Reacheable)		   | PRIVATE (Your computer)		| Descriptopn						|						 |");
                    sb.AppendFormat(
                        "\n+------+----------------------+--------+-----------------------+--------+------------------------------------+-------------------------+");
                    sb.AppendFormat("\n|	  | IP Address		   | Port   | IP Address			| Port   |									| Expires				 |");
                    sb.AppendFormat(
                        "\n+------+----------------------+--------+-----------------------+--------+------------------------------------+-------------------------+");
                    return(device.GetAllMappingsAsync());
                })
                .Unwrap()
                .ContinueWith(task =>
                {
                    foreach (var mapping in task.Result)
                    {
                        sb.AppendFormat("\n|  {5} | {0,-20} | {1,6} | {2,-21} | {3,6} | {4,-35}|{6,25}|",
                                        ip, mapping.PublicPort, mapping.PrivateIP, mapping.PrivatePort, mapping.Description,
                                        mapping.Protocol == Protocol.Tcp ? "TCP" : "UDP", mapping.Expiration.ToLocalTime());
                    }
                    sb.AppendFormat(
                        "\n+------+----------------------+--------+-----------------------+--------+------------------------------------+-------------------------+");
                    sb.AppendFormat("\n[Removing TCP mapping] {0}:1700 -> 127.0.0.1:1600", ip);
                    return(device.DeletePortMapAsync(new Mapping(Protocol.Tcp, 1600, 1700)));
                })
                .Unwrap()
                .ContinueWith(task =>
                {
                    sb.AppendFormat("\n[Done]");
                    Console.WriteLine(sb.ToString());
                    Console.WriteLine("");
                    Console.WriteLine("Socket listening on port 1602. Remember, it is mapped to external port 1702!!!");
                    Console.WriteLine("Test it with http://www.canyouseeme.org/ online tool");

                    var endPoint = new IPEndPoint(IPAddress.Any, 1602);
                    var socket   = new Socket(endPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
                    socket.Bind(endPoint);
                    socket.Listen(4);

                    socket.Close();
                    Console.WriteLine("Press any key to exit...");
                });
            }, TaskContinuationOptions.OnlyOnRanToCompletion);

            try
            {
                t.Wait();
            }
            catch (AggregateException e)
            {
                if (e.InnerException is NatDeviceNotFoundException)
                {
                    Console.WriteLine("Not found");
                    Console.WriteLine("Press any key to exit...");
                }
            }
            Console.ReadKey();
        }