Пример #1
1
 private void AddMap(ref INatDevice device, Protocol ptype, int localport, int publicport, string description)
 {
     try
     {
         Mapping mapper = null;
         mapper = new Mapping(Protocol.Tcp, localport, publicport);
         mapper.Description = description;
         device.CreatePortMap(mapper);
     }
     catch (MappingException)
     {
         MessageBox.Show("Sorry, something went wrong.\n"
             + "Could not add the port due to an error.\n"
             + "This error may occur because the port is already taken\n"
             + "or the port lies within a not allowed range.\n\n"
             + "Try a different port, for example above 1024.", "Error...");
     }
     catch (Exception e)
     {
         MessageBox.Show("An unknown error occurred. The content of the error is:\n\n" + e.ToString(), "Error...");
     }
 }
        private void DeviceFound(object sender, DeviceEventArgs args)
        {
            Mapping minecraftTCP = new Mapping(Protocol.Tcp, 25565, 25565);
            Mapping minecraftUDP = new Mapping(Protocol.Udp, 25565, 25565);

            minecraftTCP.Description = "MinecraftTCP";
            minecraftUDP.Description = "MinecraftUDP";


            device = args.Device;
            try
            {
                device.DeletePortMap(minecraftTCP);
                device.DeletePortMap(minecraftUDP);
            }
            catch {
            }
            device.CreatePortMap(minecraftTCP);
            device.CreatePortMap(minecraftUDP);
            device.CreatePortMap(new Mapping(Protocol.Udp, 2, 2));

            // on device found code

            //cport.Text = "okay";
        }
Пример #3
0
        private void DeviceFound(object sender, DeviceEventArgs args)
        {
            try
            {
                INatDevice device = args.Device;

                //remove existing port maps that exist on the ports we want
                foreach (Mapping portMap in device.GetAllMappings())
                {
                    if (externalPorts.Contains(portMap.PublicPort))
                    {
                        Console.WriteLine("Deleting " + portMap.PublicPort.ToString());
                        device.DeletePortMap(portMap);
                    }
                }

                //add the ports we want for our IP
                for (int i = 0; i <= 2; i++)
                {
                    Console.WriteLine("Creating IP: " + device.LocalAddress.ToString() + " port: " + i.ToString());
                    device.CreatePortMap(new Mapping(Protocol.Tcp, internalPorts[i], externalPorts[i]));
                }
            }
            catch (Exception e)
            {
            }
        }
Пример #4
0
        public static void DeviceFound(object sender, DeviceEventArgs args)
        {
            if (args.Device == null)
            {
                return;
            }

            Log.Write("server", "NAT device discovered.");

            Game.Settings.Server.NatDeviceAvailable = true;
            Game.Settings.Server.AllowPortForward   = true;

            try
            {
                NatDevice = args.Device;
                Log.Write("server", "Type: {0}", NatDevice.GetType());
                Log.Write("server", "Your external IP is: {0}", NatDevice.GetExternalIP());

                foreach (var mp in NatDevice.GetAllMappings())
                {
                    Log.Write("server", "Existing port mapping: protocol={0}, public={1}, private={2}",
                              mp.Protocol, mp.PublicPort, mp.PrivatePort);
                }
            }
            catch (Exception e)
            {
                Log.Write("server", "Can't fetch information from NAT device: {0}", e);

                Game.Settings.Server.NatDeviceAvailable = false;
                Game.Settings.Server.AllowPortForward   = false;
            }
        }
Пример #5
0
 private void OnDeviceFound(object sender, DeviceEventArgs args)
 {
     upnpdev = args.Device;
     //upnpdev.CreatePortMap(new Mapping(Protocol.Tcp, 4444, 4444));
     Rendezvous.GetInstance().PublishInfo(string.Format("{0} {1}",
                                                        upnpdev.GetExternalIP().ToString(), upnpdev.LocalAddress.ToString()));
 }
Пример #6
0
        public static void DeviceFound(object sender, DeviceEventArgs args)
        {
            if (args.Device == null)
                return;

            Log.Write("server", "NAT device discovered.");

            Game.Settings.Server.NatDeviceAvailable = true;
            Game.Settings.Server.AllowPortForward = true;

            try
            {
                NatDevice = args.Device;
                Log.Write("server", "Type: {0}", NatDevice.GetType());
                Log.Write("server", "Your external IP is: {0}", NatDevice.GetExternalIP());

                foreach (var mp in NatDevice.GetAllMappings())
                    Log.Write("server", "Existing port mapping: protocol={0}, public={1}, private={2}",
                              mp.Protocol, mp.PublicPort, mp.PrivatePort);
            }
            catch (Exception e)
            {
                Log.Write("server", "Can't fetch information from NAT device: {0}", e);

                Game.Settings.Server.NatDeviceAvailable = false;
                Game.Settings.Server.AllowPortForward = false;
            }
        }
        private void CreatePortMap(INatDevice device, List <Mapping> currentMappings, int privatePort, int publicPort)
        {
            var hasMapping = false;

            if (currentMappings != null)
            {
                hasMapping = currentMappings.Any(i => i.PublicPort == publicPort && i.PrivatePort == privatePort);
            }
            else
            {
                try
                {
                    var mapping = device.GetSpecificMapping(Protocol.Tcp, publicPort);
                    hasMapping = mapping != null;
                }
                catch (NotSupportedException)
                {
                }
            }

            if (!hasMapping)
            {
                _logger.Debug("Creating port map on port {0}", privatePort);
                device.CreatePortMap(new Mapping(Protocol.Tcp, privatePort, publicPort)
                {
                    Description = _appHost.Name
                });
            }
        }
        private void CreateRules(INatDevice device)
        {
            // On some systems the device discovered event seems to fire repeatedly
            // This check will help ensure we're not trying to port map the same device over and over

            List <Mapping> currentMappings = null;

            try
            {
                currentMappings = device.GetAllMappings().ToList();
            }
            catch (NotSupportedException)
            {
            }

            var address = device.LocalAddress.ToString();

            if (!_createdRules.Contains(address))
            {
                _createdRules.Add(address);

                CreatePortMap(device, currentMappings, _appHost.HttpPort, _config.Configuration.PublicPort);
                CreatePortMap(device, currentMappings, _appHost.HttpsPort, _config.Configuration.PublicHttpsPort);
            }
        }
Пример #9
0
        private void DeviceLost(object sender, DeviceEventArgs args)
        {
            INatDevice device = args.Device;

            Console.WriteLine("Device Lost");
            Console.WriteLine("Type: {0}", device.GetType().Name);
        }
Пример #10
0
        private async void CreateRules(INatDevice device)
        {
            if (_disposed)
            {
                throw new ObjectDisposedException("PortMapper");
            }

            // On some systems the device discovered event seems to fire repeatedly
            // This check will help ensure we're not trying to port map the same device over and over

            var address = device.LocalAddress.ToString();

            lock (_createdRules)
            {
                if (!_createdRules.Contains(address))
                {
                    _createdRules.Add(address);
                }
                else
                {
                    return;
                }
            }

            var success = await CreatePortMap(device, _appHost.HttpPort, _config.Configuration.PublicPort).ConfigureAwait(false);

            if (success)
            {
                await CreatePortMap(device, _appHost.HttpsPort, _config.Configuration.PublicHttpsPort).ConfigureAwait(false);
            }
        }
Пример #11
0
        void refresh()
        {
            if (devices.Count == 0)
            {
                MessageBox.Show("Devices not yet found.", "", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            Invoke((MethodInvoker) delegate
            {
                lstPorts.Items.Clear();

                for (int i = 0; i < devices.Count; i++)
                {
                    INatDevice device = devices[i];
                    Mapping[] maps    = device.GetAllMappings();
                    foreach (Mapping map in maps)
                    {
                        ListViewItem item = new ListViewItem();
                        item.Text         = map.PrivatePort.ToString();
                        item.SubItems.Add(map.PublicPort.ToString());
                        item.SubItems.Add(map.Protocol.ToString());
                        item.Tag = device;
                        lstPorts.Items.Add(item);
                    }
                }
            });
        }
Пример #12
0
        public static IAsyncResult BeginGetSpecificMapping(this INatDevice device, Protocol protocol, int externalPort, AsyncCallback callback, object asyncState)
        {
            var result = new TaskAsyncResult(device.GetSpecificMappingAsync(protocol, externalPort), callback, asyncState);

            result.Task.ContinueWith(t => result.Complete(), TaskScheduler.Default);
            return(result);
        }
Пример #13
0
        private void DeviceFound(object sender, DeviceEventArgs args)
        {
            try
            {
                INatDevice device = args.Device;

                logger.Fatal("UPNP Enabled Device found");
                logger.Info("Type: {0}", device.GetType().Name);
                logger.Info("External IP: {0}", device.GetExternalIP());

                Mapping mapping = new Mapping(Protocol.Udp, Convert.ToInt32(uxServerPortUdp.Text), Convert.ToInt32(uxServerPortUdp.Text));
                device.CreatePortMap(mapping);
                logger.Info("Create Mapping: protocol={0}, public={1}, private={2}", mapping.Protocol, mapping.PublicPort, mapping.PrivatePort);
                try
                {
                    Mapping m = device.GetSpecificMapping(Protocol.Udp, Convert.ToInt32(uxServerPortUdp.Text));
                    logger.Info("Testing port Mapping passed: protocol={0}, public={1}, private={2}", m.Protocol, m.PublicPort, m.PrivatePort);
                    // Se il portfoward funziona interrompiamo il discovery
                    // NOTA: rileviamo solo il primo router della lista
                    NatUtility.StopDiscovery();
                }
                catch
                {
                    logger.Fatal("Could not get specific mapping");
                }
            }
            catch (Exception ex)
            {
                logger.Fatal(ex.Message);
                logger.Fatal(ex.StackTrace);
            }
        }
Пример #14
0
        private void btAdd_Click(object sender, EventArgs e)
        {
            if (lvDevices.SelectedItems.Count > 0)
            {
                INatDevice device = GetDeviceByUUID(lvDevices.SelectedItems[0].SubItems[3].Text);
                AddMapping map    = new AddMapping();

                map.ShowDialog();
                if (map.success)
                {
                    if (map.protocol == AddMapping.AddPortOptions.Both)
                    {
                        AddMap(ref device, Protocol.Tcp, map.localport, map.publicport, map.description);
                        AddMap(ref device, Protocol.Udp, map.localport, map.publicport, map.description);
                    }
                    else if (map.protocol == AddMapping.AddPortOptions.TCP)
                    {
                        AddMap(ref device, Protocol.Tcp, map.localport, map.publicport, map.description);
                    }
                    else if (map.protocol == AddMapping.AddPortOptions.UDP)
                    {
                        AddMap(ref device, Protocol.Udp, map.localport, map.publicport, map.description);
                    }
                    UpdateMappings(lvDevices.SelectedItems[0].SubItems[3].Text);
                }
            }
            else
            {
                MessageBox.Show("Please select a device from the devices list to add the portmap to", "Oops...");
            }
        }
Пример #15
0
        public static IAsyncResult BeginDeletePortMap(this INatDevice device, Mapping mapping, AsyncCallback callback, object asyncState)
        {
            var result = new TaskAsyncResult(device.DeletePortMapAsync(mapping), callback, asyncState);

            result.Task.ContinueWith(t => result.Complete(), TaskScheduler.Default);
            return(result);
        }
Пример #16
0
        public void DeviceLost(object sender, DeviceEventArgs args)
        {
            INatDevice device = args.Device;

            logger.Fatal("Device Lost");
            logger.Fatal("Type: {0}", device.GetType().Name);
        }
Пример #17
0
    void Start()
    {
        NatUtility.DeviceFound += (s, ea) =>
        {
            natDevice = ea.Device;

            //string externalIp;
            //try
            //{
            //    externalIp = natDevice.GetExternalIP().ToString();
            //}
            //catch (Exception ex)
            //{
            //    Debug.Log("Failed to get external IP :\n" + ex.ToString());
            //    externalIp = "UNKNOWN";
            //}

            //if (WanIP == "UNKNOWN")
            //{
            //    Debug.Log("Reverted to UPnP device's external IP");
            //    WanIP = externalIp;
            //}
        };
        NatUtility.DeviceLost += (s, ea) => { natDevice = null; };

        NatUtility.StartDiscovery();
    }
Пример #18
0
        public string GetExternalIp()
        {
            if (!string.IsNullOrEmpty(_cachedIp))
            {
                return(_cachedIp);
            }
            if (!UPnPAvailable)
            {
                return(null);
            }

            INatDevice dev = Devices[0];

            string external = null;

            try
            {
                var ip = dev.GetExternalIP();
                if (ip == null)
                {
                    throw new NullReferenceException();
                }
                external = ip.ToString();
            }
            catch (NullReferenceException)
            {
                return(null);
            }

            return(_cachedIp = external);
        }
Пример #19
0
 public NatDeviceWrapper(INatDevice device, IPAddress externalIP, NatProtocol type)
 {
     this.Device     = device;
     this.ExternalIP = externalIP;
     this.Type       = type;
     this.TypeName   = Type == NatProtocol.Upnp ? "UPnP" : "NAT-PMP";
 }
Пример #20
0
    void OnApplicationQuit()
    {
        if (natDevice != null)
        {
            try
            {
                if (udpMapping != null)
                {
                    natDevice.DeletePortMap(udpMapping);
                }
                if (tcpMapping != null)
                {
                    natDevice.DeletePortMap(tcpMapping);
                }
                tcpMapping = udpMapping = null;
                Debug.Log("Deleted port mapping");
            }
            catch (Exception ex)
            {
                Debug.Log("Failed to delete port mapping");
            }
        }
        NatUtility.StopDiscovery();

        CloseServer();

        natDevice = null;
    }
        private void DeviceFound(object sender, DeviceEventArgs args)
        {
            if (btnOpenWasClicked == true)
            {
                INatDevice device       = args.Device;
                Mapping    minecraftTCP = new Mapping(Protocol.Tcp, 25565, 25565);
                Mapping    minecraftUDP = new Mapping(Protocol.Udp, 25565, 25565);
                minecraftTCP.Description = "MinecraftTCP";
                minecraftUDP.Description = "MinecraftUDP";
                device.CreatePortMap(minecraftTCP);
                device.CreatePortMap(minecraftUDP);


                foreach (Mapping portMap in device.GetAllMappings())
                {
                    Debug.Print(portMap.ToString());
                }

                MessageBox.Show("Port 25565 has been opened.");
                MessageBoxResult diag = MessageBox.Show("This is the IP you will give to your friends: " + device.GetExternalIP().ToString() + ":25565" + " Do you wanna copy the IP? ",
                                                        "Success", MessageBoxButton.YesNo, MessageBoxImage.Information);

                if (diag == MessageBoxResult.Yes)
                {
                    Thread thread = new Thread(() => Clipboard.SetText(device.GetExternalIP() + ":25565"));
                    thread.SetApartmentState(ApartmentState.STA); //Set the thread to STA
                    thread.Start();
                    thread.Join();                                //Wait for the thread to end
                }
            }
        }
 private void OnDeviceFound(object sender, Nat.DeviceEventArgs args)
 {
     logger.Info("UPnP Device found");
     // FIXME: What happens if more then one device is found? Yeeek, bad news
     device = args.Device;
     MapPort();
 }
Пример #23
0
    private void DeviceFound(object sender, DeviceEventArgs e)
    {
        INatDevice device = e.Device;

        UIConsole.Log ("Found NAT device. External IP is " + device.GetExternalIP());
        _device = device;
    }
Пример #24
0
        public static IAsyncResult BeginGetAllMappings(this INatDevice device, AsyncCallback callback, object asyncState)
        {
            var result = new TaskAsyncResult(device.GetAllMappingsAsync(), callback, asyncState);

            result.Task.ContinueWith(t => result.Complete(), TaskScheduler.Default);
            return(result);
        }
Пример #25
0
        /// <summary>
        /// Deal with a found NAT device.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void NatUtility_DeviceFound(object sender, DeviceEventArgs e)
        {
            // This is the upnp enabled router
            INatDevice device = e.Device;

            if (upnpEnabled.Checked)
            {
                // Create a mapping to forward the external port
                device.CreatePortMap(new Mapping(Protocol.Tcp, Int32.Parse(txtHostPort.Text), Int32.Parse(txtHostPort.Text)));
            }
            else
            {
                //foreach (Mapping mp in device.GetAllMappings())
                //    device.DeletePortMap(mp);
            }

            /*
             * // Retrieve the details for the port map for external port 3000
             * Mapping m = device.GetSpecificMapping(Protocol.Tcp, Int32.Parse(txtHostPort.Text));
             *
             * // Get all the port mappings on the device and delete them
             * foreach (Mapping mp in device.GetAllMappings())
             *  device.DeletePortMap(mp);
             *
             * // Get the external IP address
             * IPAddress externalIP = device.GetExternalIP();
             */
        }
Пример #26
0
        private void upnp_device_found(object sender, DeviceEventArgs args)
        {
            INatDevice dev    = args.Device;
            IPAddress  pub_ip = null;

            try
            {
                pub_ip = dev.GetExternalIP();
            }
            catch (Exception)
            {
                device    = null;
                public_ip = null;
            }
            if (dev != null && pub_ip != null)
            {
                lock (this)
                {
                    this.device    = dev;
                    this.public_ip = pub_ip;
                }
                xbs_messages.addInfoMessage(" @ UPnP device found. external IP: " + pub_ip, xbs_message_sender.UPNP);
            }
            else
            {
                xbs_messages.addInfoMessage(" @ UPnP discovery failed. Could not get public IP", xbs_message_sender.UPNP, xbs_message_type.WARNING);
            }
        }
Пример #27
0
        void DeviceFound(object sender, DeviceEventArgs args)
        {
            // This is the upnp enabled router
            INatDevice device = args.Device;

            // Create a mapping to forward external port 3000 to local port 1500
            device.CreatePortMap(new Mono.Nat.Mapping(Mono.Nat.Protocol.Tcp, Properties.Settings.Default.listenPort, Properties.Settings.Default.listenPort));
        }
Пример #28
0
        private void DeviceFound(object sender, DeviceEventArgs args)
        {
            this.Router      = args.Device;
            this.RouterFound = true;

            // Send a ping as soon as router is found
            this.OnTimer(null, null);
        }
Пример #29
0
        private void DeviceFound(object sender, DeviceEventArgs args)
        {
            INatDevice device = args.Device;

            device.CreatePortMap(new Mapping(Protocol.Udp, MessagePort, MessagePort));
            device.CreatePortMap(new Mapping(Protocol.Udp, CallPort, CallPort));
            device.CreatePortMap(new Mapping(Protocol.Udp, CallReceivePort, CallReceivePort));
        }
Пример #30
0
        private void Setup(INatDevice mainNatDevice)
        {
            _mainNatDevice = mainNatDevice;

            ExternalIp = mainNatDevice.GetExternalIP();

            mainNatDevice.CreatePortMap(PortMap);
        }
 private void CreatePortMap(INatDevice device, int privatePort, int publicPort)
 {
     _logger.Debug("Creating port map on port {0}", privatePort);
     device.CreatePortMap(new Mapping(Protocol.Tcp, privatePort, publicPort)
     {
         Description = _appHost.Name
     });
 }
Пример #32
0
        private 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("Service Type: {0}", (device as UpnpNatDevice).ServiceType);

                Console.WriteLine("IP: {0}", device.GetExternalIP());
                device.CreatePortMap(new Mapping(Protocol.Tcp, 15001, 15001));
                Console.WriteLine("---");

                //return;
                /******************************************/
                /*         Advanced test suite.           */
                /******************************************/

                // Try to create a new port map:
                var mapping = new Mapping(Protocol.Tcp, 6001, 6001);
                device.CreatePortMap(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 = device.GetSpecificMapping(Protocol.Tcp, 6001);
                    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 deleting the port we opened before:
                try {
                    device.DeletePortMap(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:
                foreach (Mapping mp in device.GetAllMappings())
                {
                    Console.WriteLine("Existing Mapping: protocol={0}, public={1}, private={2}", mp.Protocol, mp.PublicPort,
                                      mp.PrivatePort);
                }

                Console.WriteLine("External IP: {0}", device.GetExternalIP());
                Console.WriteLine("Done...");
            } catch (Exception ex) {
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.StackTrace);
            }
        }
Пример #33
0
        private void CreatePortMap(INatDevice device, int privatePort, int publicPort)
        {
            _logger.Debug("Creating port map on port {0}", privatePort);

            device.CreatePortMap(new Mapping(Protocol.Tcp, privatePort, publicPort)
            {
                Description = "Media Browser Server"
            });
        }
		public ListenPortController(UserEngineSettings engineSettings)
		{
			device = null;
			this.engineSettings = engineSettings;
			map = new Mapping(engineSettings.ListenPort, Protocol.Tcp);
			controller = new NatController();

			controller.DeviceFound += OnDeviceFound;
			
		}
Пример #35
0
 public MappedPort(
     INatDevice device,
     MappingProtocol protocol,
     int internal_port,
     int external_port,
     DateTime expiration)
 {
   this.Device       = device;
   this.Protocol     = protocol;
   this.InternalPort = internal_port;
   this.ExternalPort = external_port;
   this.Expiration   = expiration;
 }
Пример #36
0
        public static void DeviceLost(object sender, DeviceEventArgs args)
        {
            Log.Write("server", "NAT device lost.");

            if (args.Device == null)
                return;

            try
            {
                NatDevice = args.Device;
                Log.Write("server", "Type: {0}", NatDevice.GetType());
            }
            catch (Exception e)
            {
                Log.Write("server", "Can't fetch type from lost NAT device: {0}", e);
            }

            Game.Settings.Server.NatDeviceAvailable = false;
            Game.Settings.Server.AllowPortForward = false;
        }
Пример #37
0
        /// <summary>
        /// Adding devices to the list and listbox
        /// </summary>
        /// <param name="device"></param>
        private void AddDevice(INatDevice device)
        {
            if (!devices.Contains(device))
            {
                devices.Add(device);
                //listBoxDevices.Items.Add(device.ToString());
                IPAddress external = device.GetExternalIP();
                Mapping[] maps = device.GetAllMappings();

                //complicated stuff because the library only allows to display some data via .ToString() as far as I know
                string str = device.ToString();
                lvDevices.Items.Add(ReadBetween("EndPoint:", ",", str));
                lvDevices.Items[lvDevices.Items.Count-1].SubItems.Add(external.ToString());
                lvDevices.Items[lvDevices.Items.Count - 1].SubItems.Add(maps.Length.ToString());
                lvDevices.Items[lvDevices.Items.Count - 1].SubItems.Add(ReadBetween("/dyndev/uuid:", ",", str));

                //if it's the first added, select it
                if (lvDevices.Items.Count == 1)
                    lvDevices.Items[0].Selected = true;
            }
        }
Пример #38
0
        private static void DeviceFound(object sender, DeviceEventArgs args)
        {
            _device = args.Device;

            NatUtility.StopDiscovery();

            _discoveryComplete = true;

            if (_port > 0)
            {
                int outPort;
                CreatePortMap(_port, out outPort);
            }
        }
Пример #39
0
 private void CreatePortMap(INatDevice device, int privatePort, int publicPort)
 {
     _logger.Debug("Creating port map on port {0}", privatePort);
     device.CreatePortMap(new Mapping(Protocol.Tcp, privatePort, publicPort)
     {
         Description = _appHost.Name
     });
 }
Пример #40
0
        private static void InternalUnMapPort(INatDevice device, int port)
        {
            for (int i = 0; i < 2; i++)
            {
                var proto = Protocol.Tcp;
                if (i > 0)
                    proto = Protocol.Udp;

                Mapping mapping = device.GetSpecificMapping(proto, port);
                if (mapping != null && mapping.PrivatePort > 0 && mapping.PublicPort > 0)
                    device.DeletePortMap(new Mapping(proto, port, port));
            }
        }
 public NatDevice(INatDevice device, IPAddress external_ipaddress)
 {
   this.Device = device;
   this.ExternalIPAddress = external_ipaddress;
 }
Пример #42
0
        private void DeviceSetupComplete(INatDevice device)
        {
            lock (this.devices)
            {
                // We don't want the same device in there twice
                if (devices.Contains(device))
                    return;

                devices.Add(device);
            }

            OnDeviceFound(new DeviceEventArgs(device));
        }
Пример #43
0
 public DeviceEventArgs(INatDevice device)
 {
     this.device = device;
 }
Пример #44
0
    void Start()
    {
        NatUtility.DeviceFound += (s, ea) =>
        {
            natDevice = ea.Device;

            //string externalIp;
            //try
            //{
            //    externalIp = natDevice.GetExternalIP().ToString();
            //}
            //catch (Exception ex)
            //{
            //    Debug.Log("Failed to get external IP :\n" + ex.ToString());
            //    externalIp = "UNKNOWN";
            //}

            //if (WanIP == "UNKNOWN")
            //{
            //    Debug.Log("Reverted to UPnP device's external IP");
            //    WanIP = externalIp;
            //}
        };
        NatUtility.DeviceLost += (s, ea) => { natDevice = null; };

        NatUtility.StartDiscovery();
    }
Пример #45
0
 private void UnmapDevice(INatDevice device)
 {
     try
     {
         device.DeletePortMap(new Mapping(Protocol.Udp, Port, Port));
         Relay.Instance.MessageLog.AddMessage("Deleted port mapping.");
     }
     catch (MappingException)
     {
         Relay.Instance.MessageLog.AddMessage("Unable to delete port mapping. That's odd.");
     }
 }
Пример #46
0
 /// <summary>
 /// Remove the device
 /// </summary>
 /// <param name="device"></param>
 private void RemoveDevice(INatDevice device)
 {
     if (devices.Contains(device))
     {
         devices.Remove(device);
         for (int i = 0; i < lvDevices.Items.Count; i++)
         {
             if (device.ToString().Contains(lvDevices.Items[i].SubItems[3].Text))
             {
                 lvDevices.Items.Remove(lvDevices.Items[i]);
             }
         }
     }
 }
Пример #47
0
        private void DeviceFound(object sender, DeviceEventArgs args)
        {
            logger.IfInfo("Device Found");

            this.Status = NatStatus.DeviceFound;

            // This is the upnp enabled router
            this.Device = args.Device;

            // Create a mapping to forward external port to local port
            try
            {
                Device.CreatePortMap(new Mapping(Protocol.Tcp, Injection.Kernel.Get<IServerSettings>().Port, Injection.Kernel.Get<IServerSettings>().Port));
                this.Status = NatStatus.PortForwardedSuccessfully;
            }
            catch (Exception e)
            {
                this.Status = NatStatus.PortForwardingFailed;
                logger.Error("Port mapping failed", e);
            }
        }
		private void OnDeviceFound(object sender, Nat.DeviceEventArgs args)
		{
			logger.Info("UPnP Device found");
			// FIXME: What happens if more then one device is found? Yeeek, bad news
			device = args.Device;
			MapPort();
		}
        private void CreateRules(INatDevice device)
        {
            // On some systems the device discovered event seems to fire repeatedly
            // This check will help ensure we're not trying to port map the same device over and over

            var address = device.LocalAddress.ToString();

            if (!_createdRules.Contains(address))
            {
                _createdRules.Add(address);

                var info = _appHost.GetSystemInfo();

                CreatePortMap(device, info.HttpServerPortNumber);
            }
        }
Пример #50
0
 void NatUtility_DeviceFound(object sender, DeviceEventArgs e)
 {
     router = e.Device;
 }
Пример #51
0
    void OnApplicationQuit()
    {
        if (natDevice != null)
        {
            try
            {
                if (udpMapping != null)
                    natDevice.DeletePortMap(udpMapping);
                if (tcpMapping != null)
                    natDevice.DeletePortMap(tcpMapping);
                tcpMapping = udpMapping = null;
                Debug.Log("Deleted port mapping");
            }
            catch (Exception ex)
            {
                Debug.Log("Failed to delete port mapping");
            }
        }
        NatUtility.StopDiscovery();

        CloseServer();

        natDevice = null;
    }
Пример #52
0
        private void CreateRules(INatDevice device)
        {
            // On some systems the device discovered event seems to fire repeatedly
            // This check will help ensure we're not trying to port map the same device over and over

            var address = device.LocalAddress.ToString();

            if (!_createdRules.Contains(address))
            {
                _createdRules.Add(address);

                CreatePortMap(device, _appHost.HttpPort, _config.Configuration.PublicPort);
                CreatePortMap(device, _appHost.HttpsPort, _config.Configuration.PublicHttpsPort);
            }
        }
Пример #53
0
 private void DeviceSetupComplete(INatDevice device)
 {
     OnDeviceFound(new DeviceEventArgs(device));
 }
Пример #54
0
        private void CreatePortMap(INatDevice device, int port)
        {
            _logger.Debug("Creating port map on port {0}", port);

            device.CreatePortMap(new Mapping(Protocol.Tcp, port, port)
            {
                Description = "Media Browser Server"
            });
        }
Пример #55
0
 private void MapDevice(INatDevice device)
 {
     bool exists;
     try
     {
         exists = device.GetSpecificMapping(Protocol.Udp, Port).PublicPort != -1;
     }
     catch (MappingException)
     {
         exists = false;
     }
     if (exists)
     {
         Relay.Instance.MessageLog.AddMessage("Unable to create UPnP port map: port has already been mapped.\nIs a server already running on your network?");
         return;
     }
     device.CreatePortMap(new Mapping(Protocol.Udp, Port, Port));
     Relay.Instance.MessageLog.AddMessage("Created UPnP port mapping.");
 }
Пример #56
0
        private void CreateRules(INatDevice device)
        {
            var info = _appHost.GetSystemInfo();

            CreatePortMap(device, info.HttpServerPortNumber);

            if (info.WebSocketPortNumber != info.HttpServerPortNumber)
            {
                CreatePortMap(device, info.WebSocketPortNumber);
            }
        }
Пример #57
0
 private void TryRemoveDevice(INatDevice device)
 {
     for (int i = NatDevices.Count - 1; i >= 0; i--)
     {
         if (Equals(NatDevices[i], device))
         {
             if (ShouldMapNatDevices)
                 UnmapDevice(device);
             NatDevices.RemoveAt(i);
         }
     }
 }
Пример #58
0
 private void upnp_device_found(object sender, DeviceEventArgs args)
 {
     INatDevice dev = args.Device;
     IPAddress pub_ip = null;
     try
     {
         pub_ip = dev.GetExternalIP();
     }
     catch (Exception)
     {
         device = null;
         public_ip = null;
     }
     if (dev!=null && pub_ip!=null)
     {
         lock (this)
         {
             this.device = dev;
             this.public_ip = pub_ip;
         }
         xbs_messages.addInfoMessage(" @ UPnP device found. external IP: " + pub_ip, xbs_message_sender.UPNP);
     }
     else
         xbs_messages.addInfoMessage(" @ UPnP discovery failed. Could not get public IP", xbs_message_sender.UPNP, xbs_message_type.WARNING);
 }
Пример #59
0
 private static void DeviceLost(object sender, DeviceEventArgs args)
 {
     _device = null;
     _discoveryComplete = false;
 }
Пример #60
0
        private static void InternalMapPort(INatDevice device, int port)
        {
            for (int i = 0; i < 2; i++)
            {
                var proto = Protocol.Tcp;
                if (i > 0)
                    proto = Protocol.Udp;

                Mapping mapping = device.GetSpecificMapping(proto, port);
                if (mapping == null || mapping.IsExpired() || mapping.PrivatePort < 0 || mapping.PublicPort < 0)
                    device.CreatePortMap(new Mapping(proto, port, port));
            }
        }