예제 #1
0
        /// <summary>
        /// Creates a new port map.
        /// </summary>
        /// <param name="port">The port to map.</param>
        /// <param name="externalPort">The port which has been mapped, -1 if it failed.</param>
        /// <returns>True if successfull, else False.</returns>
        public static bool CreatePortMap(int port, out int externalPort)
        {
            if (!_discoveryComplete)
            {
                externalPort = -1;
                return(false);
            }

            try
            {
                Mapping mapping = new Mapping(Protocol.Tcp, port, port);

                for (int i = 0; i < 3; i++)
                {
                    _device.CreatePortMapAsync(mapping);
                }

                if (_mappings.ContainsKey(mapping.PrivatePort))
                {
                    _mappings[mapping.PrivatePort] = mapping;
                }
                else
                {
                    _mappings.Add(mapping.PrivatePort, mapping);
                }

                externalPort = mapping.PublicPort;
                return(true);
            }
            catch (MappingException)
            {
                externalPort = -1;
                return(false);
            }
        }
예제 #2
0
        public static IAsyncResult BeginCreatePortMap(this INatDevice device, Mapping mapping, AsyncCallback callback, object asyncState)
        {
            var result = new TaskAsyncResult(device.CreatePortMapAsync(mapping), callback, asyncState);

            result.Task.ContinueWith(t => result.Complete(), TaskScheduler.Default);
            return(result);
        }
예제 #3
0
파일: Main.cs 프로젝트: nagyist/Mono.Nat
        private async void DeviceFound(object sender, DeviceEventArgs args)
        {
            try
            {
                INatDevice device = args.Device;

                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("Device found");
                Console.ResetColor();
                Console.WriteLine("Type: {0}", device.GetType().Name);

                Console.WriteLine("IP: {0}", await device.GetExternalIPAsync());
                await device.CreatePortMapAsync(new Mapping(Protocol.Tcp, 1500, 1500));

                Console.WriteLine("---");

                return;

                Mapping mapping = new Mapping(Protocol.Tcp, 6001, 6001);
                await device.CreatePortMapAsync(mapping);

                Console.WriteLine("Create Mapping: protocol={0}, public={1}, private={2}", mapping.Protocol, mapping.PublicPort, mapping.PrivatePort);

                try
                {
                    Mapping m = await device.GetSpecificMappingAsync(Protocol.Tcp, 6001);

                    Console.WriteLine("Specific Mapping: protocol={0}, public={1}, private={2}", m.Protocol, m.PublicPort, m.PrivatePort);
                }
                catch
                {
                    Console.WriteLine("Couldnt get specific mapping");
                }
                foreach (Mapping mp in await device.GetAllMappingsAsync())
                {
                    Console.WriteLine("Existing Mapping: protocol={0}, public={1}, private={2}", mp.Protocol, mp.PublicPort, mp.PrivatePort);
                    await device.DeletePortMapAsync(mp);
                }

                Console.WriteLine("External IP: {0}", await device.GetExternalIPAsync());
                Console.WriteLine("Done...");
            } catch (Exception ex) {
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.StackTrace);
            }
        }
예제 #4
0
        private Task <Mapping> CreatePortMap(INatDevice device, int privatePort, int publicPort)
        {
            _logger.LogDebug(
                "Creating port map on local port {0} to public port {1} with device {2}",
                privatePort,
                publicPort,
                device.DeviceEndpoint);

            return(device.CreatePortMapAsync(
                       new Mapping(Protocol.Tcp, privatePort, publicPort, 0, _appHost.Name)));
        }
예제 #5
0
        private async void DeviceFound(object sender, DeviceEventArgs e)
        {
            await locker.WaitAsync();

            try
            {
                device  = e.Device;
                mapping = new Mapping(Protocol.Tcp, Program.settings.Port, Program.settings.Port, 0, "ElectronChat");
                await device.CreatePortMapAsync(mapping);

                Console.WriteLine("Succesfully added UPNP entry");
            }
            catch (Exception) {}
            locker.Release();
        }
예제 #6
0
        async Task CreateOrFailMapping(INatDevice device, Mapping mapping)
        {
            var map = new Mono.Nat.Mapping(
                mapping.Protocol == Protocol.Tcp ? Mono.Nat.Protocol.Tcp : Mono.Nat.Protocol.Udp,
                mapping.PrivatePort,
                mapping.PublicPort
                );

            try {
                await device.CreatePortMapAsync(map);

                Mappings = Mappings.WithCreated(mapping);
            } catch {
                Mappings = Mappings.WithFailed(mapping);
            }
        }
예제 #7
0
        private async void DeviceFound(object sender, DeviceEventArgs args)
        {
            try
            {
                INatDevice device = args.Device;
                await device.CreatePortMapAsync(new Mapping(Protocol.Udp, 11000, 11000, (int)TimeSpan.FromDays(1).TotalSeconds, "Nitrox Server - Subnautica"));

                Log.Info($"Server port has been automatically opened on your router");
            }
#if DEBUG
            catch (Exception ex)
            {
                Log.Error($"Automatic port forwarding failed: {ex}");
            }
#else
            catch (Exception)
            {
                Log.Error("Automatic port forwarding failed, please manually port forward");
            }
#endif
        }
예제 #8
0
        private async Task CreatePortMap(INatDevice device, int privatePort, int publicPort)
        {
            _logger.LogDebug(
                "Creating port map on local port {LocalPort} to public port {PublicPort} with device {DeviceEndpoint}",
                privatePort,
                publicPort,
                device.DeviceEndpoint);

            try
            {
                var mapping = new Mapping(Protocol.Tcp, privatePort, publicPort, 0, _appHost.Name);
                await device.CreatePortMapAsync(mapping).ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                _logger.LogError(
                    ex,
                    "Error creating port map on local port {LocalPort} to public port {PublicPort} with device {DeviceEndpoint}.",
                    privatePort,
                    publicPort,
                    device.DeviceEndpoint);
            }
        }
        private static async void DeviceFound(object sender, DeviceEventArgs args)
        {
            try
            {
                //Get Device Info
                device = args.Device;
                //Debug.Log("Device Protocol: " + device.NatProtocol);
                //Debug.Log("Device Name: " + device.GetType().Name);
                //Debug.Log("Device External IP: " + (await device.GetExternalIPAsync()).ToString());

                //Create Mapping
                Mapping portMapping = new Mapping(Protocol.Tcp, NetServer.serverInstance.hostPort, NetServer.serverInstance.hostPort);
                //Debug.Log("Creating uPnP Mapping: protocol=" + portMapping.Protocol + "ports=" + portMapping.PublicPort);
                Mapping createdMap = await device.CreatePortMapAsync(portMapping);

                Debug.Log("Created Map: protocol=" + createdMap.Protocol + "ports=" + createdMap.PublicPort);
                currentMapping = createdMap;

                //try
                //{
                //    foreach (Mapping m in device.GetAllMappings())
                //    {
                //        Debug.Log("Retrieved uPnP Mapping: protocol=" + m.Protocol + "ports=" + m.PublicPort);
                //    }
                //}
                //catch (System.Exception e)
                //{
                //    Debug.LogError("Couldn't get specific mapping... " + e);
                //}
            }
            catch (System.Exception e)
            {
                Debug.LogError(e);
            }
            NatUtility.StopDiscovery();
        }
예제 #10
0
        private async Task ApplyPortMappings(bool refresh = false)
        {
            if (natDevice == null)
            {
                return;
            }

            if (!refresh)
            {
                // Remove the old mappings.
                await RemovePortMappings();

                // Setup the new mappings.
                SetupReferenceMappings();
            }

            // Create the mappings.
            for (int i = 0; i < 2; i++)
            {
                Mapping mapping = referenceMappings[i];
                if (mapping == null)
                {
                    break;
                }

                // Create mapping.
                Mapping result;
                try {
                    result = await natDevice.CreatePortMapAsync(referenceMappings[i]);
                }
                catch (Exception e) {
                    Debug.WriteLine("Failed to create port mapping: {0}", e);
                    ShowMessage("Failed to create port mapping", e.Message, MessageBoxIcon.Error);
                    await RemoveMappingsWithUI();

                    return;
                }

                // Check mapping.
                if (mapping.Equals(result))
                {
                    activeMappings[i] = result;
                }
                else
                {
                    // Something went wrong, revert.
                    Debug.WriteLine("Created mapping not equal\n  expected: {0}\n  actual: {1}", mapping, result);
                    ShowMessage("Failed to create port mapping", "The port mapping that was created by the NAT device differs from the requested one.", MessageBoxIcon.Error);
                    await RemoveMappingsWithUI();

                    return;
                }
            }

            if (!refresh)
            {
                // Start refresh timer if needed.
                if (lifetime > 0 && refreshInterval > 0)
                {
                    refreshTimer.Interval = (double)refreshInterval * 1000;
                    refreshTimer.Start();
                }

                mappedInfo.Text = "Yes";
            }
        }
예제 #11
0
 public static Mapping CreatePortMap(this INatDevice device, Mapping mapping)
 {
     return(device.CreatePortMapAsync(mapping).GetAwaiter().GetResult());
 }
예제 #12
0
        private async void DeviceFound(object sender, DeviceEventArgs args)
        {
            await locker.WaitAsync();

            try {
                INatDevice device = args.Device;

                // Only interact with one device at a time. Some devices support both
                // upnp and nat-pmp.

                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("Device found: {0}", device.NatProtocol);
                Console.ResetColor();
                Console.WriteLine("Type: {0}", device.GetType().Name);

                Console.WriteLine("IP: {0}", await device.GetExternalIPAsync());

                Console.WriteLine("---");

                //return;

                /******************************************/
                /*         Advanced test suite.           */
                /******************************************/

                // Try to create a new port map:
                var mapping = new Mapping(Protocol.Tcp, 6001, 6011);
                await device.CreatePortMapAsync(mapping);

                Console.WriteLine("Create Mapping: protocol={0}, public={1}, private={2}", mapping.Protocol, mapping.PublicPort,
                                  mapping.PrivatePort);

                // Try to retrieve confirmation on the port map we just created:
                try {
                    Mapping m = await device.GetSpecificMappingAsync(Protocol.Tcp, mapping.PublicPort);

                    Console.WriteLine("Specific Mapping: protocol={0}, public={1}, private={2}", m.Protocol, m.PublicPort,
                                      m.PrivatePort);
                } catch {
                    Console.WriteLine("Couldn't get specific mapping");
                }

                // Try retrieving all port maps:
                try {
                    var mappings = await device.GetAllMappingsAsync();

                    if (mappings.Length == 0)
                    {
                        Console.WriteLine("No existing uPnP mappings found.");
                    }
                    foreach (Mapping mp in mappings)
                    {
                        Console.WriteLine("Existing Mappings: protocol={0}, public={1}, private={2}", mp.Protocol, mp.PublicPort, mp.PrivatePort);
                    }
                } catch {
                    Console.WriteLine("Couldn't get all mappings");
                }

                // Try deleting the port we opened before:
                try {
                    await device.DeletePortMapAsync(mapping);

                    Console.WriteLine("Deleting Mapping: protocol={0}, public={1}, private={2}", mapping.Protocol, mapping.PublicPort, mapping.PrivatePort);
                } catch {
                    Console.WriteLine("Couldn't delete specific mapping");
                }

                // Try retrieving all port maps:
                try {
                    var mappings = await device.GetAllMappingsAsync();

                    if (mappings.Length == 0)
                    {
                        Console.WriteLine("No existing uPnP mappings found.");
                    }
                    foreach (Mapping mp in mappings)
                    {
                        Console.WriteLine("Existing Mapping: protocol={0}, public={1}, private={2}", mp.Protocol, mp.PublicPort, mp.PrivatePort);
                    }
                } catch {
                    Console.WriteLine("Couldn't get all mappings");
                }

                Console.WriteLine("External IP: {0}", await device.GetExternalIPAsync());
                Console.WriteLine("Done...");
            } finally {
                locker.Release();
            }
        }