Пример #1
0
        public static bool OpenPort(int port, string name = "EPSP Client")
        {
            try
            {
                var discoverer = new NatDiscoverer();
                var cts        = new CancellationTokenSource(5000);
                var deviceTask = discoverer.DiscoverDeviceAsync(PortMapper.Upnp, cts);
                deviceTask.Wait();
                var device  = deviceTask.Result;
                var mapTask = device.CreatePortMapAsync(new Mapping(Protocol.Tcp, port, port, name));
                mapTask.Wait();
            }
            catch (AggregateException e)
            {
                if (e.InnerException is NatDeviceNotFoundException || e.InnerException is MappingException)
                {
                    return(false);
                }
                if (e.InnerException is WebException)
                {
                    return(false);
                }
                throw e;
            }

            return(true);
        }
Пример #2
0
        public static async Task InitializeAsync(TimeSpan timeout)
        {
            if (Status != UPnPStatus.Uninitialized)
            {
                throw new InvalidOperationException($"{nameof(InitializeAsync)} can only be called in status {UPnPStatus.Uninitialized}.");
            }

            var natDiscoverer = new NatDiscoverer();
            var token         = new CancellationTokenSource(timeout);

            try
            {
                NatDevice = await natDiscoverer.DiscoverDeviceAsync(PortMapper.Upnp, token);

                Status = UPnPStatus.Enabled;
            }
            catch (NatDeviceNotFoundException)
            {
                Logger.Info("Failed to find UPnP device.");
                Status = UPnPStatus.Disabled;
                return;
            }

            ExternalIP = await NatDevice.GetExternalIPAsync();
        }
Пример #3
0
    // Server
    public void Host()
    {
        isHost = true;
        host   = new Player(PlayerPrefs.GetString("PlayerName", "GUEST"), Team.White, isHost);

        Task t = Task.Run(async() => {
            NatDiscoverer discoverer    = new NatDiscoverer();
            CancellationTokenSource cts = new CancellationTokenSource(5000);
            NatDevice device            = await discoverer.DiscoverDeviceAsync(PortMapper.Upnp, cts);
            await device.CreatePortMapAsync(new Mapping(Protocol.Tcp, port, port, "Hexachessagon (Session lifetime)"));
        });

        try {
            t.Wait();
        } catch (Exception e) {
            Debug.LogWarning(e);
        }

        server = TcpListener.Create(port);

        try {
            server.Start();
            server.BeginAcceptTcpClient(new AsyncCallback(AcceptClientCallback), server);
        }
        catch (Exception e) {
            Debug.LogWarning($"Failed to host on {ip}:{port} with error:\n{e}");
        }

        LoadLobby(Lobby.Type.Host);
    }
Пример #4
0
        /// <summary>	Removes the port mapping. </summary>
        /// <exception cref="UpnpException">	Thrown when an Upnp error condition occurs. </exception>
        /// <param name="privatePort">	    The private port. </param>
        /// <param name="ipAddress">
        ///     (Optional) The IP address. If NULL - local ip will be
        ///     assumed.
        /// </param>
        /// <returns>	A Task. </returns>
        public async Task RemovePortMapping(int privatePort, IPAddress ipAddress = null)
        {
            try
            {
                if (ipAddress == null)
                {
                    ipAddress = LocalIpAddress;
                }

                var discoverer = new NatDiscoverer();
                var cts        = new CancellationTokenSource(UpnpTimeout);
                var device     = await discoverer.DiscoverDeviceAsync(PortMapper.Upnp, cts);

                var mapping = await GetPortMapping(privatePort, ipAddress);

                if (mapping != null)
                {
                    await device.DeletePortMapAsync(new Mapping(Protocol.Tcp,
                                                                IPAddress.Parse(mapping.PrivatecIpAddress),
                                                                mapping.PrivatePort, mapping.PublicPort, int.MaxValue, mapping.Name));
                }
            }
            catch (NatDeviceNotFoundException e)
            {
                throw new UpnpException(ExceptionMessages.DeviceNotFound, e);
            }
        }
Пример #5
0
        public async void StopUPNP()
        {
            try
            {
                var nat    = new NatDiscoverer();
                var cts    = new CancellationTokenSource(5000);
                var device = await nat.DiscoverDeviceAsync(PortMapper.Upnp, cts);

                foreach (var mapping in await device.GetAllMappingsAsync())
                {
                    if (mapping.Description.Contains("RBXLegacy"))
                    {
                        await device.DeletePortMapAsync(mapping);
                    }
                }

                var ip = await device.GetExternalIPAsync();

                ConsolePrint("Port " + GlobalVars.ServerPort.ToString() + " removed from device " + ip, 2);
            }
            catch (NatDeviceNotFoundException e)
            {
                ConsolePrint("Error: " + e.ToString(), 2);
            }
        }
Пример #6
0
        public void Start()
        {
            _networkManager              = GameObject.FindObjectOfType <CustomNetworkManager>();
            _networkManager.networkPort  = CustomNetworkManager.DefaultPort;
            _networkManager.offlineScene = "MainMenu";

            var dropDown = LevelPacksDropDown.GetComponent <Dropdown>();
            var options  = new List <Dropdown.OptionData>();

            foreach (var levelPack in LevelPacks)
            {
                options.Add(new Dropdown.OptionData(string.Format("{0}", levelPack.Name)));
            }
            OnLevelPackChanged(0);

            dropDown.AddOptions(options);

#if UNITY_STANDALONE
            try
            {
                var discoverer = new NatDiscoverer();
                var cts        = new CancellationTokenSource();
                var device     = discoverer.DiscoverDeviceAsync(PortMapper.Upnp, cts);
                device.Wait(cts.Token);
                device.Result.CreatePortMapAsync(new Mapping(Protocol.Tcp, 15678, 15678, "GDGP"));
            }
            catch
            {
                Debug.LogWarning("UPnP port opening failed");
            }
#endif
        }
Пример #7
0
        public async void StartUPNP()
        {
            try
            {
                var nat = new NatDiscoverer();

                var cts    = new CancellationTokenSource(5000);
                var device = await nat.DiscoverDeviceAsync(PortMapper.Upnp, cts);

                await device.CreatePortMapAsync(new Mapping(Protocol.Udp, GlobalVars.ServerPort, GlobalVars.ServerPort, "RBXLegacy"));

                var ip = await device.GetExternalIPAsync();

                ConsolePrint("Port " + GlobalVars.ServerPort.ToString() + " registered to device " + ip, 3);
            }
            catch (NatDeviceNotFoundException e)
            {
                ConsolePrint("Error: " + e.ToString(), 2);
            }
            catch (MappingException me)
            {
                switch (me.ErrorCode)
                {
                case 718:
                    ConsolePrint("The external port is already in use.", 2);
                    break;

                case 728:
                    ConsolePrint("The router's mapping table is full.", 2);
                    break;
                }
            }
        }
        private bool ExecuteCommand(string message)
        {
            var command = message.Remove(0, 1).ToLower();

            message = message.Remove(0, 1);

            if (command.StartsWith("stop"))
            {
                Program.LastRunTime = DateTime.UtcNow;
                Stop();
                NatDiscoverer.ReleaseAll();

                Console.WriteLine();
                Console.WriteLine("Stopped the server. Press any key to continue...");
                Console.ReadKey();
            }

            else if (command.StartsWith("clear"))
            {
                Console.Clear();
            }

            else
            {
                return(Server.Services.GetService <CommandManagerService>()?.ExecuteServerCommand(message) == true);
            }

            return(true);
        }
Пример #9
0
        public void OnShutdown()
        {
            if (_requestShutdown)
            {
                return;
            }

            _requestShutdown = true;
            if (_portMapping == null)
            {
                return;
            }

            Monitor.Enter(_natUpnpCreateLocker);
            Task.Run(async() => {
                try {
                    var discoverer = new NatDiscoverer();
                    var cts        = new CancellationTokenSource(10000);
                    var device     = await discoverer.DiscoverDeviceAsync(PortMapper.Upnp, cts);
                    Logger.Info("Removing UPnP mapping");
                    await device.DeletePortMapAsync(_portMapping);
                } catch (Exception e) {
                    Logger.Error("Unable to remove UPnP mapping!", e);
                } finally {
                    _portMapping = null;
                }
            }).Wait();

            Monitor.Exit(_natUpnpCreateLocker);

            _socket?.Close();
            _socket?.Dispose();
        }
Пример #10
0
        private async void NATForwarding()
        {
            if (!NATForwardingEnabled)
            {
                return;
            }

            try
            {
                Logger.Log(LogType.Info, "Initializing NAT Discovery.");
                var discoverer = new NatDiscoverer();
                Logger.Log(LogType.Info, "Getting your external IP. Please wait...");
                var device = await discoverer.DiscoverDeviceAsync();

                Logger.Log(LogType.Info, $"Your external IP is {device.GetExternalIPAsync().Wait(new CancellationTokenSource(2000))}.");

                foreach (var module in Server.Services.GetService <ModuleManagerService>().GetModuleSettings().Where(module => module.Enabled && module.Port != 0))
                {
                    Logger.Log(LogType.Info, $"Forwarding port {module.Port}.");
                    device.CreatePortMapAsync(new Mapping(Protocol.Tcp, module.Port, module.Port, "PokeD Port Mapping")).Wait(new CancellationTokenSource(2000).Token);
                }
            }
            catch (NatDeviceNotFoundException)
            {
                Logger.Log(LogType.Error, "No NAT device is present or, Upnp is disabled in the router or Antivirus software is filtering SSDP (discovery protocol).");
            }
        }
Пример #11
0
        public static async Task OpenPort(Protocol protocol, int privatePort, int publicPort, string description)
        {
            NatDiscoverer discoverer = new NatDiscoverer();
            NatDevice     device     = await discoverer.DiscoverDeviceAsync();

            await device.CreatePortMapAsync(new Mapping(protocol, privatePort, publicPort, description));
        }
Пример #12
0
        static async Task <string> SetupPortMappings(int port)
        {
            string publicIP = "";

            try
            {
                var discoverer = new NatDiscoverer();

                // using SSDP protocol, it discovers NAT device.
                var NATDevice = await discoverer.DiscoverDeviceAsync();

                var ExternalIP = await NATDevice.GetExternalIPAsync();

                publicIP = ExternalIP.ToString();

                // create a new mapping in the router [external_ip:port -> host_machine:port]
                await NATDevice.CreatePortMapAsync(new Mapping(Protocol.Tcp, port, port, "KIService"));
            }
            catch (Exception ex)
            {
                Console.WriteLine("An Error in UPnP - this service may not be available on your NAT device. Please check your router / firewall / network. UPnP is disabled. (Error : " + ex.Message + ")");
            }

            return(publicIP);
        }
Пример #13
0
        public OpenNatUpnpProvider()
        {
            var devicetask = new NatDiscoverer().DiscoverDeviceAsync();

            devicetask.Wait();
            _device = devicetask.Result;
        }
#pragma warning restore 4014

        private static async Task ForwardPortInternalAsync(ushort port, int milisecondsDelay, NetworkProtocolType networkProtocolType = NetworkProtocolType.Udp)
        {
            try
            {
                if (LastForwardedPort == port || UpnpFailed)
                {
                    return;
                }
                if (LastForwardedPort != 0)
                {
                    NatDiscoverer.ReleaseAll();
                }
                NatDiscoverer discoverer = new NatDiscoverer();
                NatDevice     device;
                using (CancellationTokenSource cts = new CancellationTokenSource(milisecondsDelay))
                {
                    device = await discoverer.DiscoverDeviceAsync(PortMapper.Upnp | PortMapper.Pmp, cts).ConfigureAwait(false);
                }

                await device.CreatePortMapAsync(new Mapping(networkProtocolType, port, port, "LiteNetLib4Mirror UPnP")).ConfigureAwait(false);

                LastForwardedPort = port;
                Debug.Log("Port forwarded successfully!");
            }
            catch
            {
                Debug.LogWarning("UPnP failed!");
                UpnpFailed = true;
            }
        }
    IEnumerator WaitDiscover()
    {
        NatDiscoverer           disc = new NatDiscoverer();
        CancellationTokenSource cts  = new CancellationTokenSource();

        cts.CancelAfter(10000);
        int gamePort = NATNetworkManager_PHP.singleton.myPort;
        Task <NatDevice> deviceTask = disc.DiscoverDeviceAsync(PortMapper.Upnp, cts);

        //deviceTask.RunSynchronously ()
        while (!deviceTask.IsCompleted && !deviceTask.IsCanceled)
        {
            yield return(new WaitForEndOfFrame());
        }
        if (deviceTask.IsCompleted)
        {
            bool hasException = false;
            try {
                device = deviceTask.Result;
            } catch (Exception ex) {
                Debug.Log("No Upnp. FurtherInfo :" + ex.ToString());
                hasException = true;
            }finally{
                if (!hasException && device != null)
                {
                    NATNetworkManager_PHP.DisplayLog("NAT DEVICE FOUND");
                    Task portMapTask = device.CreatePortMapAsync(new Mapping(Protocol.Udp, gamePort, gamePort));
                    //portMapTask.RunSynchronously ();
                    StartCoroutine("WaitUpnp", portMapTask);
                }
            }
        }
        yield return(new WaitForEndOfFrame());
    }
Пример #16
0
    public static void Delete()
    {
        var t = Task.Run(async() =>
        {
            var nat    = new NatDiscoverer();
            var cts    = new CancellationTokenSource(5000);
            var device = await nat.DiscoverDeviceAsync(PortMapper.Upnp, cts);

            var ip = await device.GetExternalIPAsync();

            await device.DeletePortMapAsync(new Mapping(Protocol.Tcp, 7777, 7777));
            Debug.Log("deletemapping");
        }

                         );

        try
        {
            t.Wait();
        }
        catch (AggregateException e)
        {
            if (e.InnerException is NatDeviceNotFoundException)
            {
                Debug.Log("Not Found");
            }
        }
    }
Пример #17
0
        public static async Task <bool> TryCreatePortMappingAsync(Server server)
        {
            if (server == null)
            {
                throw new ArgumentNullException(nameof(server));
            }

            var discoverer = new NatDiscoverer();

            try
            {
                var device = await discoverer.DiscoverDeviceAsync();

                var mappings = await device.GetAllMappingsAsync();

                if (!mappings.Any(m => m.Protocol == Protocol.Udp && m.PrivatePort == server.Port && m.PublicPort == server.Port))
                {
                    var mapping = new Mapping(Protocol.Udp, server.Port, server.Port, server.Name);
                    await device.CreatePortMapAsync(mapping);
                }

                return(true);
            }
            catch
            {
            }

            return(false);
        }
Пример #18
0
        private static async void InitNatDevice()
        {
            _natDiscoverer = new NatDiscoverer();
            var token = new CancellationTokenSource(5000);

            _natDevice = await _natDiscoverer.DiscoverDeviceAsync(PortMapper.Upnp, token);
        }
Пример #19
0
#pragma warning restore 4014

        private static async Task ForwardPortInternalAsync(ushort port, int milisecondsDelay, NetworkProtocolType networkProtocolType = NetworkProtocolType.Udp)
        {
            try
            {
                if (LastForwardedPort == port || UpnpFailed)
                {
                    return;
                }
                if (LastForwardedPort != 0)
                {
                    NatDiscoverer.ReleaseAll();
                }
                NatDiscoverer discoverer = new NatDiscoverer();
                NatDevice     device;
                using (CancellationTokenSource cts = new CancellationTokenSource(milisecondsDelay))
                {
                    device = await discoverer.DiscoverDeviceAsync(PortMapper.Upnp | PortMapper.Pmp, cts).ConfigureAwait(false);
                }

                ExternalIp = await device.GetExternalIPAsync();

                await device.CreatePortMapAsync(new Mapping(networkProtocolType, IPAddress.None, port, port, 0, ApplicationName)).ConfigureAwait(false);

                LastForwardedPort = port;
                Debug.Log($"Port {port.ToString()} forwarded successfully!");
            }
            catch (Exception ex)
            {
                //Debug.LogWarning($"UPnP failed!\n{ex.Message}\n{ex.StackTrace}");
                UpnpFailed = true;
            }
        }
Пример #20
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);
        }));
    }
Пример #21
0
        public async void StartAsync()
        {
            Listen = true;

            if (Settings.Instance.Server.TryUPnP)
            {
                Logger.Instance.Log($"Trying to open port {Settings.Instance.Server.Port} using UPnP...");
                try
                {
                    NatDiscoverer           discoverer = new NatDiscoverer();
                    CancellationTokenSource cts        = new CancellationTokenSource(2500);
                    NatDevice device = await discoverer.DiscoverDeviceAsync(PortMapper.Upnp, cts);

                    await device.CreatePortMapAsync(new Mapping(Protocol.Tcp, Settings.Instance.Server.Port, Settings.Instance.Server.Port, "BeatSaber Multiplayer ServerHub"));

                    Logger.Instance.Log($"Port {Settings.Instance.Server.Port} is open!");
                }
                catch (Exception)
                {
                    Logger.Instance.Warning($"Can't open port {Settings.Instance.Server.Port} using UPnP!");
                }
            }

            Listener.Start();
            BeginListening();
        }
Пример #22
0
    private void Disconnect()
    {
        if (isHost)
        {
            server?.Stop();
        }
        else if (client != null && client.Connected)
        {
            // Write disconnect to socket
            try {
                SendMessage(new Message(MessageType.Disconnect));
            } catch (Exception e) {
                Debug.LogWarning($"Failed to write to socket with error:\n{e}");
            }
        }

        stream?.Close();
        client?.Close();

        NatDiscoverer.ReleaseAll();

        lobby?.DisconnectRecieved();

        Debug.Log($"Disconnected.");
    }
        public static async Task <bool> Init()
        {
            if (device != null)
            {
                return(true);
            }

            var nat = new NatDiscoverer();
            var cts = new CancellationTokenSource(5000);

            try
            {
                device = await nat.DiscoverDeviceAsync(PortMapper.Upnp, cts);

                return(true);
            }
            catch
            {
                try
                {
                    device = await nat.DiscoverDeviceAsync(PortMapper.Pmp, cts);

                    return(true);
                }
                catch { }
            }

            return(false);
        }
Пример #24
0
        public static void RemovePortMapping(int port = 9657)
        {
            var discoverer = new NatDiscoverer();
            var cts        = new CancellationTokenSource();
            var device     = discoverer.DiscoverDeviceAsync(PortMapper.Upnp, cts).Result;

            device.DeletePortMapAsync(new Mapping(Protocol.Tcp, port, port, "Ur Game Port"));
        }
Пример #25
0
        public async void OpenPort()
        {
            var discoverer = new NatDiscoverer();
            var cts        = new CancellationTokenSource(15000);
            var device     = await discoverer.DiscoverDeviceAsync(PortMapper.Upnp, cts);

            await device.CreatePortMapAsync(new Mapping(Protocol.Tcp, PORT, PORT, "ClientChat"));
        }
Пример #26
0
        public static async void ForwardPort(Protocol protocol, short privatePort, short publicPort, string name)
        {
            var discoverer = new NatDiscoverer();
            var cts        = new CancellationTokenSource(10000);
            var device     = await discoverer.DiscoverDeviceAsync(PortMapper.Upnp, cts);

            await device.CreatePortMapAsync(new Mapping(protocol, privatePort, publicPort, name));
        }
Пример #27
0
        /// <summary>
        /// 删除一个Nat映射
        /// </summary>
        /// <param name="isTcp"></param>
        /// <param name="isUPnP"></param>
        /// <param name="privatePort"></param>
        /// <param name="publicPort"></param>
        /// <param name="des"></param>
        /// <param name="timeOut"></param>
        public static async void Delete(bool isTcp = true, bool isUPnP = true, int privatePort = 39654, int publicPort = 39654, string des = "SAEA.NAT", int timeOut = 10 * 1000)
        {
            var discoverer = new NatDiscoverer();
            var cts        = new CancellationTokenSource(timeOut);
            var device     = await discoverer.DiscoverDeviceAsync(isUPnP?PortMapper.Upnp : PortMapper.Pmp, cts);

            await device.DeletePortMapAsync(new Mapping(isTcp ? Protocol.Tcp : Protocol.Udp, privatePort, publicPort, des));
        }
Пример #28
0
        private void StartNatPortMapping()
        {
            var disc = new NatDiscoverer();

            nat     = disc.DiscoverDeviceAsync().Result;
            portMap = new Mapping(Protocol.Tcp, Port, Port, "Socket Server Map");
            nat?.CreatePortMapAsync(portMap).RunSynchronously();
        }
Пример #29
0
        private static async Task ForwardPorts()
        {
            var discoverer = new NatDiscoverer();
            var cts        = new CancellationTokenSource(5000);
            var device     = await discoverer.DiscoverDeviceAsync(PortMapper.Upnp, cts);

            await device.CreatePortMapAsync(new Mapping(Protocol.Tcp, Settings.GamePort, Settings.GamePort, "Temporary"));
        }
Пример #30
0
        /// <summary>	Gets public IP address. </summary>
        /// <returns>	The public IP address. </returns>
        public async Task <IPAddress> GetPublicIpAddress()
        {
            var discoverer = new NatDiscoverer();
            var cts        = new CancellationTokenSource(UpnpTimeout);
            var device     = await discoverer.DiscoverDeviceAsync(PortMapper.Upnp, cts);

            return(await device.GetExternalIPAsync());
        }
Пример #31
0
        private async static Task Test()
        {
            var nat = new NatDiscoverer();
            var cts = new CancellationTokenSource(5000);
            var device = await nat.DiscoverDeviceAsync(PortMapper.Upnp, cts);

            var sb = new StringBuilder();
            var ip = await device.GetExternalIPAsync();

            sb.AppendFormat("\nYour IP: {0}", ip);
            await device.CreatePortMapAsync(new Mapping(Protocol.Tcp, 1600, 1700, "Open.Nat (temporary)"));
            await device.CreatePortMapAsync(new Mapping(Protocol.Tcp, 1601, 1701, "Open.Nat (Session lifetime)"));
            await device.CreatePortMapAsync(new Mapping(Protocol.Tcp, 1602, 1702,  0, "Open.Nat (Permanent lifetime)"));
            await device.CreatePortMapAsync(new Mapping(Protocol.Tcp, 1603, 1703, 20, "Open.Nat (Manual lifetime)"));
            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+------+----------------------+--------+-----------------------+--------+------------------------------------+-------------------------+");
            foreach (var mapping in await device.GetAllMappingsAsync())
            {
                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);
            await device.DeletePortMapAsync(new Mapping(Protocol.Tcp, 1600, 1700));
            sb.AppendFormat("\n[Done]");


            Console.WriteLine(sb.ToString());
/*
                var mappings = await device.GetAllMappingsAsync();
                var deleted = mappings.All(x => x.Description != "Open.Nat Testing");
                Console.WriteLine(deleted
                    ? "[SUCCESS]: Test mapping effectively removed ;)"
                    : "[FAILURE]: Test mapping wan not removed!");
*/                
        }
Пример #32
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, 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());
                });
        }