Esempio n. 1
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!");
*/                
        }
Esempio n. 2
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());
                });
        }
Esempio n. 3
0
        /// <summary>
        /// Gestion de l'ouverture automatique des ports UDP pour le P2P
        /// </summary>
        /// <param name="flag"></param>
        private void InitUPNP(bool flag)
        {
            if (flag)
            {
                if (m_bUPNP)
                {
                    return;
                }
                var t = Task.Run(async() =>
                {
                    var nat = new NatDiscoverer();
                    var cts = new CancellationTokenSource();
                    try
                    {
                        Device = await nat.DiscoverDeviceAsync(PortMapper.Upnp, cts);
#if DEBUG
                        Log.LogMessage("P2PManager: Routeur UPNP détecté", Color.DarkBlue, 1);
#endif
                        await Device.CreatePortMapAsync(new Mapping(Open.Nat.Protocol.Udp, m_Port, m_Port, 0, "ffs2playP3D"));
#if DEBUG
                        Log.LogMessage("P2PManager: Ouverture du port UPNP ok", Color.DarkBlue, 1);
#endif
                    }
                    catch (AggregateException ae)
                    {
                        ae.Handle((x) =>
                        {
                            if (x is NatDeviceNotFoundException)
                            {
                                Log.LogMessage("P2PManager: Routeur UPNP introuvable", Color.DarkViolet);
                                return(true);
                            }
                            if (x is MappingException)
                            {
                                Log.LogMessage("P2PManager: Erreur lors de l'ouverture du port " + m_Port.ToString() + " : " + x.Message, Color.DarkViolet);
                                return(true);
                            }
                            return(false);
                        });
                    }
                    m_bUPNP = true;
                });
            }
            else
            {
                if ((!m_bUPNP) || (Device == null))
                {
                    return;
                }
                var t = Task.Run(async() =>
                {
                    try
                    {
                        await Device.DeletePortMapAsync(new Mapping(Open.Nat.Protocol.Udp, m_Port, m_Port));
#if DEBUG
                        Log.LogMessage("P2PManager: Fermeture du port UPNP ok", Color.DarkBlue, 1);
#endif
                    }
                    catch (AggregateException ae)
                    {
                        ae.Handle((x) =>
                        {
                            if (x is MappingException)
                            {
                                Log.LogMessage("P2PManager: Erreur lors de la fermetur du port", Color.DarkViolet);
                                return(true);
                            }
                            return(false);
                        });
                    }
                    m_bUPNP = false;
                });
            }
        }
Esempio n. 4
0
        public async Task Connect()
#endif
        {
            _server.WhenDiscoveryRequest = () =>
                                           "HTTP/1.1 200 OK\r\n"
                                           + "Server: Custom/1.0 UPnP/1.0 Proc/Ver\r\n"
                                           + "EXT:\r\n"
                                           + "Location: http://[::1]:5431/dyndev/uuid:0000e068-20a0-00e0-20a0-48a8000808e0\r\n"
                                           + "Cache-Control:max-age=1800\r\n"
                                           + "ST:urn:schemas-upnp-org:service:WANIPConnection:1\r\n"
                                           + "USN:uuid:0000e068-20a0-00e0-20a0-48a802086048::urn:schemas-upnp-org:service:WANIPConnection:1";

            _server.WhenGetExternalIpAddress = (ctx) =>
            {
                var responseXml = "<?xml version=\"1.0\"?>" +
                                  "<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\" " +
                                  "s:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">" +
                                  "<s:Body>" +
                                  "<m:GetExternalIPAddressResponse xmlns:m=\"urn:schemas-upnp-org:service:WANIPConnection:1\">" +
                                  "<NewExternalIPAddress>FE80::0202:B3FF:FE1E:8329</NewExternalIPAddress>" +
                                  "</m:GetExternalIPAddressResponse>" +
                                  "</s:Body>" +
                                  "</s:Envelope>";
                var bytes    = Encoding.UTF8.GetBytes(responseXml);
                var response = ctx.Response;
                response.OutputStream.Write(bytes, 0, bytes.Length);
                response.OutputStream.Flush();
                response.StatusCode        = 200;
                response.StatusDescription = "OK";
                response.Close();
            };

            var nat = new NatDiscoverer();

#if NET35
            var cts = new CancellationTokenSource();
            cts.CancelAfter(5000);

            NatDevice device = null;
            nat.DiscoverDeviceAsync(PortMapper.Upnp, cts)
            .ContinueWith(tt =>
            {
                device = tt.Result;
                Assert.IsNotNull(device);
            });

            device.GetExternalIPAsync()
            .ContinueWith(tt =>
            {
                var ip = tt.Result;
                Assert.AreEqual(IPAddress.Parse("FE80::0202:B3FF:FE1E:8329"), ip);
            });
#else
            var cts    = new CancellationTokenSource(5000);
            var device = await nat.DiscoverDeviceAsync(PortMapper.Upnp, cts);

            Assert.IsNotNull(device);

            var ip = await device.GetExternalIPAsync();

            Assert.AreEqual(IPAddress.Parse("FE80::0202:B3FF:FE1E:8329"), ip);
#endif
        }
        async void StartServer()
        {
            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 Server"));

                    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!");
                }
            }


            Logger.Instance.Log("Starting server...");
            _listener = new TcpListener(IPAddress.Any, Settings.Instance.Server.Port);

            _listener.Start();

            Logger.Instance.Log("Waiting for clients...");

            ServerLoopThread = new Thread(ServerLoop)
            {
                IsBackground = true
            };
            ServerLoopThread.Start();

            AcceptClientThread();

            if (Settings.Instance.Server.WSEnabled)
            {
                if (Settings.Instance.Server.TryUPnP)
                {
                    Logger.Instance.Log($"Trying to open port {Settings.Instance.Server.WSPort} 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.WSPort, Settings.Instance.Server.WSPort, "BeatSaber Multiplayer WebSocket Server"));

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

                wss = new WebSocketServer(Settings.Instance.Server.WSPort);
                wss.AddWebSocketService <Broadcast>("/");
                wss.Start();
                Logger.Instance.Log($"WebSocket Server started @ {Settings.Instance.Server.IP}:{Settings.Instance.Server.WSPort}");
            }

            Dictionary <string, int> _serverHubs = new Dictionary <string, int>();

            for (int i = 0; i < Settings.Instance.Server.ServerHubIPs.Length; i++)
            {
                if (Settings.Instance.Server.ServerHubPorts.Length <= i)
                {
                    _serverHubs.Add(Settings.Instance.Server.ServerHubIPs[i], 3700);
                }
                else
                {
                    _serverHubs.Add(Settings.Instance.Server.ServerHubIPs[i], Settings.Instance.Server.ServerHubPorts[i]);
                }
            }

            _serverHubs.AsParallel().ForAll(x =>
            {
                ServerHubClient client = new ServerHubClient();
                _serverHubClients.Add(client);

                client.Connect(x.Key, x.Value);
            }
                                            );
        }
Esempio n. 6
0
        public static async Task <int> MapPortTask(int privatePort, int publicPort)
        {
            var logFile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "OpenNat.log");

            try
            {
                if (!NatDiscoverer.TraceSource.Listeners.Contains(TextWriterTraceListener))
                {
                    NatDiscoverer.TraceSource.Listeners.Remove(TextWriterTraceListener);
                }

                TextWriterTraceListener.Close();

                if (File.Exists(logFile))
                {
                    File.Delete(logFile);
                }
            }
            catch
            {
                // ignored
            }
            NatDiscoverer.ReleaseAll();

            NatDiscoverer.TraceSource.Switch.Level = SourceLevels.All;

            if (TextWriterTraceListener == null)
            {
                TextWriterTraceListener = new TextWriterTraceListener(logFile, "OpenNatTxtLog");
            }

            if (!NatDiscoverer.TraceSource.Listeners.Contains(TextWriterTraceListener))
            {
                NatDiscoverer.TraceSource.Listeners.Add(TextWriterTraceListener);
            }

            var nat = new NatDiscoverer();

            var cts    = new CancellationTokenSource(30 * 1000); //30 Sec
            var device = await nat.DiscoverDeviceAsync(PortMapper.Upnp, cts);

            var externalIp = await device.GetExternalIPAsync();

            var allMappings = await device.GetAllMappingsAsync();

            var localIp = Dns.GetHostEntry(Dns.GetHostName()).AddressList
                          .FirstOrDefault(key => key.AddressFamily == AddressFamily.InterNetwork);

            var enumerable = allMappings as Mapping[] ?? allMappings.ToArray();

            if (enumerable.Any(key => //Equals(key.PrivateIP, localIp) && key.Description == "AOEO Project Celeste"
                               key.PublicPort == 1000))
            {
                var r = enumerable.FirstOrDefault(
                    key => //Equals(key.PrivateIP, localIp) && key.Description == "AOEO Project Celeste"
                    key.PublicPort == 1000);

                if (r != null)
                {
                    await device.DeletePortMapAsync(r);
                }
            }

            //var rnd = new Random(DateTime.UtcNow.Millisecond);
            var newPublicPort = publicPort;
            //while (enumerable.Any(key => key.PublicPort == newPublicPort))
            //    newPublicPort = rnd.Next(1000, ushort.MaxValue);

            await device.CreatePortMapAsync(new Mapping(Protocol.Udp, privatePort, newPublicPort, int.MaxValue,
                                                        "AOEO Project Celeste"));

            allMappings = await device.GetAllMappingsAsync();

            enumerable = allMappings as Mapping[] ?? allMappings.ToArray();

            var sb = new StringBuilder();

            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+------+----------------------+--------+-----------------------+--------+------------------------------------+-------------------------+");
            foreach (var mapping in enumerable)
            {
                sb.AppendFormat("\n|  {5} | {0,-20} | {1,6} | {2,-21} | {3,6} | {4,-35}|{6,25}|",
                                externalIp, mapping.PublicPort, mapping.PrivateIP, mapping.PrivatePort, mapping.Description,
                                mapping.Protocol == Protocol.Tcp ? "TCP" : "UDP", mapping.Expiration.ToLocalTime());
            }
            sb.AppendFormat(
                "\n+------+----------------------+--------+-----------------------+--------+------------------------------------+-------------------------+");

            NatDiscoverer.TraceSource.TraceInformation(sb.ToString());

            if (enumerable.Any(key => Equals(key.PrivateIP, localIp) &&
                               key.PublicPort == newPublicPort &&
                               key.PrivatePort == privatePort && key.Description == "AOEO Project Celeste"))
            {
                return(newPublicPort);
            }

            throw new Exception("Port mapping fail!");
        }
Esempio n. 7
0
        public static void ForwardPorts(PortMapper type = PortMapper.Upnp, bool retry = false)
        {
            var webServerPort   = (int)Settings.Get("WebServer").WebServerPort;
            var apiPort         = (int)Settings.Get("TaskServer").TaskServerPort;
            var webCamPort      = (int)Settings.Get("Webcams").WebcamPort;
            var terminalPort    = (int)Settings.Get("Terminal").TerminalPort;
            var screenSharePort = (int)Settings.Get("ScreenShareService").ScreenSharePort;
            var nat             = new NatDiscoverer();
            var cts             = new CancellationTokenSource();

            cts.CancelAfter(5000);
            NatDevice device;
            var       t = nat.DiscoverDeviceAsync(type, cts);

            t.ContinueWith(tt =>
            {
                device = tt.Result;
                device.GetExternalIPAsync()
                .ContinueWith(task =>
                {
                    ;
                    return(device.CreatePortMapAsync(
                               new Mapping(Protocol.Tcp, webServerPort, webServerPort, 0, "Ulterius Web Server")));
                })
                .Unwrap()
                .ContinueWith(task =>
                {
                    return(device.CreatePortMapAsync(
                               new Mapping(Protocol.Tcp, screenSharePort, screenSharePort, 0, "Ulterius Screen Share")));
                })
                .Unwrap()
                .ContinueWith(task =>
                {
                    return(device.CreatePortMapAsync(
                               new Mapping(Protocol.Tcp, apiPort, apiPort, 0, "Ulterius Api")));
                })
                .Unwrap()
                .ContinueWith(task =>
                {
                    return(device.CreatePortMapAsync(
                               new Mapping(Protocol.Tcp, webCamPort, webCamPort, 0, "Ulterius Webcams")));
                })
                .Unwrap()
                .ContinueWith(task =>
                {
                    return(device.CreatePortMapAsync(
                               new Mapping(Protocol.Tcp, terminalPort, terminalPort, 0, "Ulterius Terminal")));
                })
                .Unwrap()
                .ContinueWith(task => { Console.WriteLine("Ports forwarded!"); });
            }, TaskContinuationOptions.OnlyOnRanToCompletion);

            try
            {
                t.Wait();
            }
            catch (AggregateException e)
            {
                if (e.InnerException is NatDeviceNotFoundException)
                {
                    if (retry)
                    {
                        return;
                    }
                    ForwardPorts(PortMapper.Pmp, true);
                    Console.WriteLine("No NAT Device Found");
                }
            }
        }
Esempio n. 8
0
        private static async Task <NatDevice> DiscoverDevice()
        {
            var nat = new NatDiscoverer();

            return(await nat.DiscoverDeviceAsync(PortMapper.Upnp, new CancellationTokenSource(5000)));
        }
Esempio n. 9
0
        private static async System.Threading.Tasks.Task <bool> DiscoverOpenNatAsync()
        {
            try
            {
                var discoverer = new NatDiscoverer();

                // we don't want to discover forever, just 5 senconds or less
                var cts = new CancellationTokenSource(5000);

                // we are only interested in Upnp NATs because PMP protocol doesn't allow to list mappings
                var device = await discoverer.DiscoverDeviceAsync(PortMapper.Upnp, cts);

                foreach (var mapping in await device.GetAllMappingsAsync())
                {
                    Console.WriteLine(mapping);
                }


                foreach (var mapping in await device.GetAllMappingsAsync())
                {
                    // in this example we want to delete the "Skype" mappings
                    if (mapping.Description.Contains("OPEN"))
                    {
                        Console.WriteLine("Deleting {0}", mapping);
                        await device.DeletePortMapAsync(mapping);
                    }
                }
                // display the NAT's IP address
                Console.WriteLine("The external IP Address is: {0} ", await device.GetExternalIPAsync());

                // create a new mapping in the router [external_ip:1702 -> host_machine:1602]
                await device.CreatePortMapAsync(new Mapping(Protocol.Tcp, _openTcpPort, _openTcpPort, "Discover For OPEN"));
            }
            catch (NatDeviceNotFoundException e)
            {
                Console.WriteLine("wasn't able to find an Upnp device ;(");
                return(false);
            }
            catch (MappingException me)
            {
                switch (me.ErrorCode)
                {
                case 718:
                    Console.WriteLine("The external port already in use.");
                    StartListener_Open();
                    break;

                case 728:
                    Console.WriteLine("The router's mapping table is full.");
                    return(true);

                    break;
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                return(false);
            }
            return(true);
        }
Esempio n. 10
0
        static async System.Threading.Tasks.Task Main(string[] args)
        {
            bool isOpenPort = false;

            Console.WriteLine("© Mohammed Tanbir Hosssain \n");

            Console.WriteLine("Discover started ");
            Console.WriteLine($"N_Port:{_neoTcpPort}");
            Console.WriteLine($"O_Port:{_openTcpPort}");
            Console.WriteLine($"Local_Port:{_localTcpPort}");
            Console.WriteLine("-----------------------------");

            try
            {
                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine("Your Private Ip: {0}", IpHelper.PrivateIpAddress);
                Console.WriteLine("Your public Ip: {0}", IpHelper.PublicIpAddress);

                //----
                Console.WriteLine("-----------------------------");
                Console.WriteLine("Looking for N style discovering");
                if (DiscoverNeo())
                {
                    StartListener_Neo();
                    isOpenPort = true;
                    Console.WriteLine($"You _N_port: {_neoTcpPort}  listing. please go to https://canyouseeme.org/ and confirm.");
                }
                else
                {
                    Console.WriteLine($"Failed : Sorry _N_  port {_neoTcpPort} ");
                }
                Console.WriteLine("-----------------------------");
                Console.WriteLine("Looking for O style discovering");
                if (await DiscoverOpenNatAsync())
                {
                    //listener
                    StartListener_Open();
                    isOpenPort = true;
                    Console.WriteLine($"You _O_port: { _openTcpPort}  listing. please go to https://canyouseeme.org/ and confirm.");
                }
                else
                {
                    Console.WriteLine($"Failed : Sorry _0_  port {_openTcpPort} ");
                }
                Console.WriteLine("-----------------------------");
                Console.WriteLine("Looking for local discovering");
                if (DiscoverLocal())
                {
                    StartListener_Local();
                    Console.WriteLine($"You _L_port: { _localTcpPort}  listing. please go to https://canyouseeme.org/ and confirm.");
                }
                else
                {
                    Console.WriteLine($"Failed : Sorry _L_  port {_localTcpPort} ");
                }

                Console.WriteLine("-----------------------------");
                //Delete port
                if (isOpenPort)
                {
                    Console.WriteLine("Are you want to delete your mapping? ");
                    Console.WriteLine("Type 'Y' OR 'N'");
                    var ans = Console.ReadLine();
                    if (ans.ToLower() == "y")
                    {
                        try { await DeleteOpenPortAsync(); } catch (Exception) { }
                        try { DeleteNeoPort(); } catch (Exception) { }
                    }


                    Console.WriteLine(" UPnp Mapping List");
                    Console.WriteLine("-----------------------------");
                    var discoverer = new NatDiscoverer();

                    // we don't want to discover forever, just 5 senconds or less
                    var cts = new CancellationTokenSource(5000);

                    // we are only interested in Upnp NATs because PMP protocol doesn't allow to list mappings
                    var device = await discoverer.DiscoverDeviceAsync(PortMapper.Upnp, cts);

                    foreach (var mapping in await device.GetAllMappingsAsync())
                    {
                        Console.WriteLine(mapping);
                    }
                    Console.WriteLine("-----------------------------");
                }
            }
            catch (Exception ex)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("Discover Error occurred.", ex.Message);
                Console.WriteLine("Your router doesn't support Discover.");
                Console.WriteLine("Dont't worry , one day you will find your desire solution.");
            }
            Console.ResetColor();
            Console.WriteLine("-----------------------------");
            Console.WriteLine("Discover Finished");
            Console.ReadKey();
        }
Esempio n. 11
0
        public static void Main(string[] args)
        {
            var t = Task.Run(async() =>
            {
                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!");
 */
            });

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