Beispiel #1
1
        static void Main()
        {
            try
            {
                var nat = new NatDiscoverer();

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

                Console.WriteLine("The external IP Address is: {0} ", device.GetExternalIPAsync().Synch());

                device.CreatePortMapAsync(new Mapping(Protocol.Tcp, 1602, 1702, "MoN")).Synch();

                var mappings = device.GetAllMappingsAsync().Synch().ToList();
                foreach (var mapping in mappings)
                {
                    Console.WriteLine(mapping.Description);
                }

                Console.WriteLine();

                Console.ReadKey();

                Console.WriteLine("Cleanup test NAT forwarding");
                device.DeletePortMapAsync(mappings.FirstOrDefault(x => x.Description.Contains("MoN"))).Synch();
            }
            catch (Exception exception)
            {
                Console.WriteLine(exception.Message);
            }
        }
Beispiel #2
0
        internal async Task<bool> RemoveNatTraversalEntry(string identifier)
        {
            try
            {
                var discoverer = new NatDiscoverer();
                var cts = new CancellationTokenSource(10000);
                var device = await discoverer.DiscoverDeviceAsync(PortMapper.Upnp, cts);

                foreach (var mapping in await device.GetAllMappingsAsync())
                {
                    if (mapping.Description.Contains(identifier))
                    {
                        await device.DeletePortMapAsync(mapping);
                        return true;
                    }
                }
            }
            catch (NatDeviceNotFoundException NfExc)
            {
                //log exc
                return false;
            }
            catch (MappingException MExc)
            {
                //log exc
                return false;
            }

            return false;
        }
Beispiel #3
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"));
        }
 public void OpenExternalPort(int privatePort, int publicPort, string description)
 {
     localHostPort = privatePort;
     var timeSpan = new TimeSpan(0, 0, 0, 30);
     var cancellationTokenSource = new CancellationTokenSource(timeSpan);
     natDiscoverer = new NatDiscoverer();
     natDevice = natDiscoverer
         .DiscoverDeviceAsync(PortMapper.Upnp, cancellationTokenSource)
         .IsCompleted();
     mapping = new Mapping(Protocol.Tcp, privatePort, publicPort, description);
     natDevice
         .CreatePortMapAsync(mapping)
         .IsCompleted();
 }
 public async Task<bool> DiscoverDevices()
 {
     try
     {
         discoverer = new NatDiscoverer();
         var cts = new CancellationTokenSource(5000);
         devices = (await discoverer.DiscoverDevicesAsync(PortMapper.Upnp, cts)).ToList();
     }
     catch (Exception)
     {
         throw;
         // log?
     }
     
     return true;
 }
Beispiel #6
0
 public void Init()
 {
     try
     {
         NatDiscoverer natdisc = new NatDiscoverer();
         NatDevice natdev = natdisc.DiscoverDeviceAsync().Result;
         Mapping map = natdev.GetSpecificMappingAsync(Protocol.Tcp, TheServer.Port).Result;
         if (map != null)
         {
             natdev.DeletePortMapAsync(map).Wait();
         }
         natdev.CreatePortMapAsync(new Mapping(Protocol.Tcp, TheServer.Port, TheServer.Port, "Voxalia")).Wait();
         map = natdev.GetSpecificMappingAsync(Protocol.Tcp, TheServer.Port).Result;
         IPAddress publicIP = natdev.GetExternalIPAsync().Result;
         SysConsole.Output(OutputType.INIT, "Successfully opened server to public address " + map.PrivateIP + " or " + publicIP.ToString() + ", with port " + map.PrivatePort + ", as " + map.Description);
     }
     catch (Exception ex)
     {
         SysConsole.Output("Trying to open port " + TheServer.Port, ex);
     }
     if (Socket.OSSupportsIPv6)
     {
         try
         {
             ListenSocket = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp);
             ListenSocket.SetSocketOption(SocketOptionLevel.IPv6, (SocketOptionName)27 /* IPv6Only */, false);
             ListenSocket.Bind(new IPEndPoint(IPAddress.IPv6Any, TheServer.Port));
         }
         catch (Exception ex)
         {
             SysConsole.Output("Opening IPv6/IPv4 combo-socket", ex);
             ListenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
             ListenSocket.Bind(new IPEndPoint(IPAddress.Any, TheServer.Port));
         }
     }
     else
     {
         ListenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
         ListenSocket.Bind(new IPEndPoint(IPAddress.Any, TheServer.Port));
     }
     ListenSocket.Listen(100);
     ListenThread = new Thread(new ThreadStart(ListenLoop));
     ListenThread.Name = Program.GameName + "_v" + Program.GameVersion + "_NetworkListenThread";
     ListenThread.Start();
 }
Beispiel #7
0
        private static 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$(SolutionDir).");
                var device = discoverer.DiscoverDeviceAsync().Wait(new CancellationTokenSource(10000));
                Logger.Log(LogType.Info, $"Your external IP is {device.GetExternalIPAsync().Wait(new CancellationTokenSource(2000))}.");

                foreach (var module in Server.Modules.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).");
            }
        }
Beispiel #8
0
        internal async Task<bool> CreateNatTraversalEntry(NatMappingEntry entry)
        {
            try
            {
                var discoverer = new NatDiscoverer();
                var cts = new CancellationTokenSource(10000);
                var device = await discoverer.DiscoverDeviceAsync(PortMapper.Upnp, cts);

                Mapping mapping = new Mapping((Protocol)((int)entry.Protocol), entry.PrivatePort, entry.PublicPort, entry.Description);
                await device.CreatePortMapAsync(mapping);

                return true;
            }
            catch (NatDeviceNotFoundException NfExc)
            {
                //log exc
                return false;
            }
            catch (MappingException MExc)
            {
                //log exc
                return false;
            }
        }
        private async void Window_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                try
                {
                    var discoverer = new NatDiscoverer();
                    var cts = new CancellationTokenSource(10000);
                    var device = await discoverer.DiscoverDeviceAsync(PortMapper.Upnp, cts);
                    var externTest = await device.GetExternalIPAsync();
                    await device.DeletePortMapAsync(new Mapping(Protocol.Tcp, myPort, myPort, "ShareStuffChat"));
                    await device.DeletePortMapAsync(new Mapping(Protocol.Tcp, (myPort + 1), (myPort + 1), "ShareStuffFile"));
                    await device.CreatePortMapAsync(new Mapping(Protocol.Tcp, myPort, myPort, "ShareStuffChat"));
                    await device.CreatePortMapAsync(new Mapping(Protocol.Tcp, (myPort + 1), (myPort + 1), "ShareStuffFile"));
                    string foo = externTest.ToString();
                    lblMyIPAndPort.Text = "Your IP Is: " + foo + "  Your Port Is: " + myPort;
                }
                catch (Exception)
                {
                    lblMyIPAndPort.Text = "Could Not Auto Configure or Get IP";
                }
                Progress<string> progStatusBar = new Progress<string>();
                progStatusBar.ProgressChanged += (a, b) =>
                {
                    lblStatus.Text = b;
                };
                Progress<double> progUpdateBar = new Progress<double>();
                progUpdateBar.ProgressChanged += (a, b) =>
                {
                    progBar.Value = b;
                };

                Task.Factory.StartNew(() => Listen());
                Task.Factory.StartNew(() => Listen2(progStatusBar, progUpdateBar));
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
Beispiel #10
0
        /// <summary>
        /// Open the NAT port for the current Terraria ip:port
        /// </summary>
        public static void OpenPort()
        {
#if ENABLE_NAT && Full_API
            if (Terraria.Netplay.UseUPNP)
            {
                Terraria.Netplay.portForwardIP = Terraria.Netplay.GetLocalIPAddress();
                Terraria.Netplay.portForwardPort = Terraria.Netplay.ListenPort;

//                Mono.Nat.NatUtility.DeviceFound += NatUtility_DeviceFound;
//                Mono.Nat.NatUtility.StartDiscovery();

                var th = new System.Threading.Thread(async () =>
                    {
                        System.Threading.Thread.CurrentThread.Name = "NAT";
                        try
                        {
                            var discoverer = new NatDiscoverer();
                            _cancel = new CancellationTokenSource(10000);
                            _device = await discoverer.DiscoverDeviceAsync(PortMapper.Upnp, _cancel);

                            if (_device != null)
                            {
                                var ip = await _device.GetExternalIPAsync();

                                var existing = await _device.GetSpecificMappingAsync(Protocol.Tcp, Terraria.Netplay.portForwardPort);
                                if (existing != null && existing.PublicPort == Terraria.Netplay.portForwardPort)
                                {
                                    ProgramLog.Admin.Log("Detected an existing NAT map record for {0} on IP {1}", NatMapName, ip);
                                }
                                else
                                {
                                    await _device.CreatePortMapAsync(new Mapping(Protocol.Tcp, Terraria.Netplay.portForwardPort, Terraria.Netplay.portForwardPort, NatMapName));
                                    ProgramLog.Admin.Log("Created a new NAT map record for {0} on IP {1}", NatMapName, ip);
                                }
                                Terraria.Netplay.portForwardOpen = true;
                            }
                            else ProgramLog.Admin.Log("Failed to find a NAT device");
                        }
                        catch (Exception e)
                        {
                            ProgramLog.Log(e, "Failed to create NAT device mapping");
                        }
                    });
                th.Start();
            }
#endif

            //if (Netplay.mappings != null)
            //{
            //    foreach (IStaticPortMapping staticPortMapping in Netplay.mappings)
            //    {
            //        if (staticPortMapping.InternalPort == Netplay.portForwardPort && staticPortMapping.InternalClient == Netplay.portForwardIP && staticPortMapping.Protocol == "TCP")
            //        {
            //            Netplay.portForwardOpen = true;
            //        }
            //    }
            //    if (!Netplay.portForwardOpen)
            //    {
            //        Netplay.mappings.Add(Netplay.portForwardPort, "TCP", Netplay.portForwardPort, Netplay.portForwardIP, true, "Terraria Server");
            //        Netplay.portForwardOpen = true;
            //    }
            //}
        }
Beispiel #11
0
 /// <summary>
 /// Open requested port via UPnP
 /// </summary>
 /// <param name="port">Port number</param>
 /// <param name="appName">Application name</param>
 private async void NatF(int port, string appName)
 {
     var discoverer = new NatDiscoverer();
     var device = await discoverer.DiscoverDeviceAsync();
     await device.CreatePortMapAsync(new Mapping(Protocol.Tcp, port, port, appName));
 }
Beispiel #12
0
        public async Task<IEnumerable<Mapping>> GetAllMappings()
        {
            IEnumerable<Mapping> mappings = null;

            try
            {
                var discoverer = new NatDiscoverer();
                var cts = new CancellationTokenSource(10000);

                var device = await discoverer.DiscoverDeviceAsync(PortMapper.Upnp, cts);
                mappings = await device.GetAllMappingsAsync();
            }
            catch (NatDeviceNotFoundException NfExc)
            {
                //log exc
                return null;
            }
            catch (MappingException MExc)
            {
                //log exc
                return null;
            }

            return mappings;
        }
Beispiel #13
0
        //public void WaitForConnection(int publicPort)
        //{
        //    // configure a TCP socket listening on port 1602
        //    var endPoint = new IPEndPoint(IPAddress.Any, publicPort);
        //    var socket = new Socket(endPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
        //    socket.SetIPProtectionLevel(IPProtectionLevel.Unrestricted);
        //    socket.Bind(endPoint);

        //    socket.Listen(4);
        //}

        public async Task<IPAddress> GetExternalIPAddress()
        {
            IPAddress ip = null;

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

                ip = await device.GetExternalIPAsync();
            }
            catch (AggregateException e)
            {
                if (e.InnerException is NatDeviceNotFoundException)
                {
                    
                }
            }

            return ip;
        }