コード例 #1
0
ファイル: Main.cs プロジェクト: tralivali1234/Mono.Nat
        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);
            }
        }
コード例 #2
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);
            }
        }
コード例 #3
0
ファイル: UPnPWrapper.cs プロジェクト: trananh1992/sm64o
        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);
        }
コード例 #4
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);
            }
        }
        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
                }
            }
        }
コード例 #6
0
ファイル: NATUPnP.cs プロジェクト: AadityaGupta/gea-PRISM
 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()));
 }
コード例 #7
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;
            }
        }
コード例 #8
0
        void MapDevice()
        {
            if (natdevice == null)
            {
                return;
            }
            ExternalIP = natdevice.GetExternalIP();

            try
            {
                var mapping = new Mapping(Protocol.Udp, Port, Port);
                natdevice.CreatePortMap(mapping);

                if (!mappedPort)
                {
                    Invoke(delegate
                    {
                        var message = string.Format("Succesfully mapped port {0} from external IP address {1} to this machine", Port, ExternalIP);
                        Client.OnMessage(new ClientMessageArgs(message, null));
                    });
                    mappedPort = true;
                }
            }
            catch (Exception ex)
            {
                Invoke(delegate
                {
                    Client.OnMessage(new ClientMessageArgs(ex.Message, null));
                });
            }
        }
コード例 #9
0
ファイル: UPnP.cs プロジェクト: Generalcamo/OpenRA
        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;
            }
        }
コード例 #10
0
        private void Setup(INatDevice mainNatDevice)
        {
            _mainNatDevice = mainNatDevice;

            ExternalIp = mainNatDevice.GetExternalIP();

            mainNatDevice.CreatePortMap(PortMap);
        }
コード例 #11
0
ファイル: Main.cs プロジェクト: besser82/Mono.Nat
        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("IP: {0}", device.GetExternalIP());
                device.CreatePortMap(new Mapping(Protocol.Tcp, 1500, 1500));
                Console.WriteLine("---");

                return;

                Mapping 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
                {
                    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("Couldnt get specific mapping");
                }
                foreach (Mapping mp in device.GetAllMappings())
                {
                    Console.WriteLine("Existing Mapping: protocol={0}, public={1}, private={2}", mp.Protocol, mp.PublicPort, mp.PrivatePort);
                    device.DeletePortMap(mp);
                }

                Console.WriteLine("External IP: {0}", device.GetExternalIP());
                Console.WriteLine("Done...");
            } catch (Exception ex) {
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.StackTrace);
            }
        }
コード例 #12
0
    private void DeviceFound(object sender, DeviceEventArgs args)
    {
        INatDevice device = args.Device;

        NatDevices.Add(device);
        if (ShouldMapNatDevices)
        {
            MapDevice(device);
        }

        DetectedExternalAddress = device.GetExternalIP().ToString();
        OnDetectedExternalAddressChanged(DetectedExternalAddress);
    }
コード例 #13
0
        private void DeviceFound(object sender, DeviceEventArgs args)
        {
            INatDevice device = device = args.Device;

            device.CreatePortMap(new Mapping(Mono.Nat.Protocol.Tcp, this.port, this.port));

            foreach (Mapping portMap in device.GetAllMappings())
            {
                Console.WriteLine(portMap.ToString());
            }

            Console.WriteLine(device.GetExternalIP().ToString());
        }
コード例 #14
0
        private void DeviceFound(object sender, DeviceEventArgs args)
        {
            device = args.Device;

            // on device found code
            Console.WriteLine(device.GetExternalIP().ToString());


            device.CreatePortMap(new Mapping(Protocol.Tcp, obj.Client_Port, obj.Client_Port, 100000));
            device.CreatePortMap(new Mapping(Protocol.Udp, obj.Client_Port, obj.Client_Port, 100000));



            obj.Public_IP = device.GetExternalIP();
            Console.WriteLine(device.GetExternalIP().ToString());


            foreach (Mapping portMap in device.GetAllMappings())
            {
                Console.WriteLine(portMap.ToString());
            }
        }
コード例 #15
0
        private void DeviceFound(object sender, DeviceEventArgs args)
        {
            try {
                INatDevice device = args.Device;

                fLogger.WriteInfo("Device found, type: {0}", device.GetType().Name);
                if (device.GetType().Name == "PmpNatDevice")
                {
                    fLogger.WriteInfo("Device skipped");
                    return;
                }

                fLogger.WriteInfo("External IP: {0}", device.GetExternalIP());

                try {
                    Mapping m;

                    /*Mapping m = device.GetSpecificMapping(Mono.Nat.Protocol.Tcp, ProtocolHelper.PublicTCPPort);
                     * if (m != null) {
                     *  fLogger.WriteInfo("Specific Mapping: protocol={0}, public={1}, private={2}", m.Protocol, m.PublicPort, m.PrivatePort);
                     * } else {*/
                    /*m = new Mapping(Protocol.Tcp, ProtocolHelper.PublicTCPPort, ProtocolHelper.PublicTCPPort);
                     * device.CreatePortMap(m);
                     * fLogger.WriteInfo("Create Mapping: protocol={0}, public={1}, private={2}", m.Protocol, m.PublicPort, m.PrivatePort);*/
                    //}

                    m = device.GetSpecificMapping(Protocol.Udp, DHTClient.PublicDHTPort);
                    if (m != null)
                    {
                        try {
                            device.DeletePortMap(m);
                        } catch {
                        }
                    }
                    m = new Mapping(Protocol.Udp, DHTClient.PublicDHTPort, DHTClient.PublicDHTPort);
                    device.CreatePortMap(m);
                    fLogger.WriteInfo("Create Mapping: protocol={0}, public={1}, private={2}", m.Protocol, m.PublicPort, m.PrivatePort);
                } catch (Exception ex) {
                    fLogger.WriteError("Couldn't create specific mapping", ex);
                }

                foreach (Mapping mp in device.GetAllMappings())
                {
                    fLogger.WriteInfo("Existing Mapping: protocol={0}, public={1}, private={2}", mp.Protocol, mp.PublicPort, mp.PrivatePort);
                }

                fUPnPSem.Release();
            } catch (Exception ex) {
                fLogger.WriteError("NATMapper.DeviceFound()", ex);
            }
        }
コード例 #16
0
        private void DeviceFound(object sender, DeviceEventArgs args)
        {
            INatDevice device = device = args.Device;

            device.CreatePortMap(new Mapping(Protocol.Tcp, Epicoin.getport, Epicoin.getport));
            device.CreatePortMap(new Mapping(Protocol.Tcp, Epicoin.mineport, Epicoin.mineport));
            device.CreatePortMap(new Mapping(Protocol.Tcp, Epicoin.peerport, Epicoin.peerport));
            device.CreatePortMap(new Mapping(Protocol.Tcp, Epicoin.transport, Epicoin.transport));

            foreach (Mapping portMap in device.GetAllMappings())
            {
                Console.WriteLine(portMap.ToString());
            }

            Console.WriteLine(device.GetExternalIP().ToString());
        }
コード例 #17
0
        private static void DeviceFound(object sender, DeviceEventArgs args)
        {
            INatDevice device = args.Device;

            foreach (var port in UPnP._port)
            {
                device.CreatePortMap(new Mapping(Mono.Nat.Protocol.Tcp, port, port));
            }

            foreach (Mapping portMap in device.GetAllMappings())
            {
                Console.WriteLine(portMap.ToString());
            }

            Console.WriteLine(device.GetExternalIP().ToString());
        }
コード例 #18
0
        private static void DeviceFound(object sender, DeviceEventArgs args)
        {
            try {
                INatDevice device = args.Device;

                fLogger.WriteInfo("Device found");
                fLogger.WriteInfo("Type: {0}", device.GetType().Name);
                fLogger.WriteInfo("External IP: {0}", device.GetExternalIP());

                try {
                    Mapping m = device.GetSpecificMapping(Mono.Nat.Protocol.Tcp, ProtocolHelper.PublicTCPPort);
                    if (m != null)
                    {
                        fLogger.WriteInfo("Specific Mapping: protocol={0}, public={1}, private={2}", m.Protocol, m.PublicPort, m.PrivatePort);
                    }
                    else
                    {
                        m = new Mapping(Mono.Nat.Protocol.Tcp, ProtocolHelper.PublicTCPPort, ProtocolHelper.PublicTCPPort);
                        device.CreatePortMap(m);
                        fLogger.WriteInfo("Create Mapping: protocol={0}, public={1}, private={2}", m.Protocol, m.PublicPort, m.PrivatePort);
                    }

                    m = device.GetSpecificMapping(Mono.Nat.Protocol.Udp, DHTClient.PublicDHTPort);
                    if (m != null)
                    {
                        fLogger.WriteInfo("Specific Mapping: protocol={0}, public={1}, private={2}", m.Protocol, m.PublicPort, m.PrivatePort);
                    }
                    else
                    {
                        m = new Mapping(Mono.Nat.Protocol.Udp, DHTClient.PublicDHTPort, DHTClient.PublicDHTPort);
                        device.CreatePortMap(m);
                        fLogger.WriteInfo("Create Mapping: protocol={0}, public={1}, private={2}", m.Protocol, m.PublicPort, m.PrivatePort);
                    }
                } catch {
                    fLogger.WriteInfo("Couldnt get specific mapping");
                }

                foreach (Mapping mp in device.GetAllMappings())
                {
                    fLogger.WriteInfo("Existing Mapping: protocol={0}, public={1}, private={2}", mp.Protocol, mp.PublicPort, mp.PrivatePort);
                }

                fLogger.WriteInfo("Done...");
            } catch (Exception ex) {
                fLogger.WriteError("NATMapper.DeviceFound()", ex);
            }
        }
コード例 #19
0
ファイル: UPnP.cs プロジェクト: huwpascoe/OpenRA
        public static IPAddress GetExternalIP()
        {
            if (natDevice == null)
            {
                return(null);
            }

            try
            {
                return(natDevice.GetExternalIP());
            }
            catch (Exception e)
            {
                Log.Write("server", "Failed to get the external IP from NAT device: {0}", e);
                return(null);
            }
        }
コード例 #20
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 Mapping(Protocol.Tcp, 1500, 3000));
        // Retrieve the details for the port map for external port 3000
        Mapping m = device.GetSpecificMapping(Protocol.Tcp, 3000);

        // 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();
    }
コード例 #21
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;
            }
        }
コード例 #22
0
        private void DeviceFound(object sender, DeviceEventArgs args)
        {
            INatDevice device = args.Device;

            PublicIP.Invoke(new Action(() => PublicIP.Text = device.GetExternalIP().ToString()));

            if (isStarted == true)
            {
                if (portEnabled.Value == true)
                {
                    device.GetSpecificMapping(Protocol.Tcp, Convert.ToInt32(portTxt.Text));

                    device.CreatePortMap(new Mapping(Protocol.Tcp, Convert.ToInt32(portTxt.Text), Convert.ToInt32(portTxt.Text)));
                }
                else
                {
                    device.GetSpecificMapping(Protocol.Tcp, 10578);

                    device.CreatePortMap(new Mapping(Protocol.Tcp, 10578, 10578));
                }
            }
        }
コード例 #23
0
        public void DeviceFound(object sender, DeviceEventArgs args)
        {
            try
            {
                INatDevice device = args.Device;

                logger.Info("Trovato dispositivo con UPNP abilitato.");
                logger.Info("Tipo: {0}", device.GetType().Name);
                logger.Info("IP Esterno del dispositivo: {0}", device.GetExternalIP());

                Mapping mapTcp = new Mapping(Protocol.Tcp, Convert.ToInt32(tcpport), Convert.ToInt32(tcpport));
                logger.Info("Creazione del PortMapping sul dispositivo UPNP: Protocollo={0}, Porta Public={1}, private={2}", mapTcp.Protocol, mapTcp.PublicPort, mapTcp.PrivatePort);
                device.CreatePortMap(mapTcp);

                Mapping mapUdp = new Mapping(Protocol.Udp, Convert.ToInt32(udpport), Convert.ToInt32(udpport));
                logger.Info("Creazione del PortMapping sul dispositivo UPNP: Protocollo={0}, Porta Public={1}, private={2}", mapUdp.Protocol, mapUdp.PublicPort, mapUdp.PrivatePort);
                device.CreatePortMap(mapUdp);

                Mapping mapTcp2 = device.GetSpecificMapping(Protocol.Tcp, Convert.ToInt32(tcpport));
                PortMappingOkTcp = true;
                logger.Info("Verifica del PortMapping Protocollo={0}, Porta={1} passata con successo", mapTcp2.Protocol, mapTcp2.PublicPort);

                Mapping mapUdp2 = device.GetSpecificMapping(Protocol.Udp, Convert.ToInt32(udpport));
                PortMappingOkUdp = true;
                logger.Info("Verifica del PortMapping Protocollo={0}, Porta={1} passata con successo", mapUdp2.Protocol, mapUdp2.PublicPort);

                // Se il portfoward funziona interrompiamo il discovery
                // NOTA: rileviamo solo il primo router della lista
                NatUtility.StopDiscovery();
            }
            catch (Exception ex)
            {
                logger.Fatal("Procedura UPNP Fallita.");

                logger.Fatal(ex.Message);
                logger.Fatal(ex.StackTrace);
            }
        }
コード例 #24
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;
                }
            }
        }
コード例 #25
0
        public async System.Threading.Tasks.Task <dynamic> SendAsync(INatDevice Router, string ApiKey, string Key)
        {
            try
            {
                this.ExternalIP = Router.GetExternalIP().ToString();
            }
            catch (Exception exc)
            {
                Debug.WriteLine(exc.Message);
                this.ExternalIP = "";
            }

            string Hostname = Dns.GetHostName();

            this.IsPortMapped = StaticHelpers.isPortMappedOnRouter(Router);

            ManagementObject os     = new ManagementObject("Win32_OperatingSystem=@");
            string           serial = (string)os["SerialNumber"];

            var values = new Dictionary <string, string>
            {
                { "status", IsPortMapped ? "open" : "closed" },
                { "rdpopen", StaticHelpers.isRDPAvailable() ? "1" : "0" },
                { "wanip", this.ExternalIP != null ? this.ExternalIP : "" },
                { "lanip", StaticHelpers.GetInternalIP() },
                { "port", Registry.Get("Port") },
                { "host", Hostname },
                { "interval", Registry.Get("Interval") },
                { "lifetime", Registry.Get("PortLifetime") },
                { "version", StaticHelpers.GetVersion() },
                { "guid", serial },
                { "serviceinstalled", StaticHelpers.IsServiceInstalled().ToString() },
                { "servicerunning", StaticHelpers.IsServiceRunning().ToString() }
            };

            var serializer = new JavaScriptSerializer();

            var content = new FormUrlEncodedContent(new Dictionary <string, string>
            {
                { "hostid", StaticHelpers.GetHostHash(Hostname) },
                { "apikey", ApiKey },
                { "payload", Harpocrates.Engine.Encrypt(serializer.Serialize(values), Key) }
            });

            // HttpWebRequest request = WebRequest.Create(Endpoint) as HttpWebRequest;
            // request.Proxy = new WebProxy(MyProxyHostString, MyProxyPort);

            // Send the API call
            HttpClient client   = new HttpClient();
            dynamic    response = await client.PostAsync(Endpoint, content);

            // Parse out the account TTL header
            IEnumerable <string> ttls;

            if (response.Headers.TryGetValues("ttl", out ttls))
            {
                foreach (string ttl in ttls)
                {
                    this.LifeTime = Int32.Parse(ttl);
                }
            }

            // Parse out version header
            IEnumerable <string> versions;

            if (response.Headers.TryGetValues("version", out versions))
            {
                foreach (string version in versions)
                {
                    this.Version = version;
                }
            }

            this.CommandWasProcessed = ProcessCommandHeader(Router, response, Key);

            // Create the machines List
            string responseString = await response.Content.ReadAsStringAsync();

            List <Dictionary <string, string> > RemoteMachinesRaw = new JavaScriptSerializer().Deserialize <List <Dictionary <string, string> > >(responseString);

            // If there was some error parsing the json, just quit here...
            if (RemoteMachinesRaw == null)
            {
                return(response);
            }

            foreach (var a in RemoteMachinesRaw)
            {
                RemoteMachineImportJson parsed;

                // First try to decrypt one return parameter for this machine
                // If decryption fails then other machine probably has different key
                try
                {
                    string payloadDecrypted = Harpocrates.Engine.Decrypt(a["payload"], Key);
                    parsed = serializer.Deserialize <RemoteMachineImportJson>(payloadDecrypted);
                }
                catch
                {
                    continue;
                }

                RemoteMachine x = new RemoteMachine();

                x.wanip            = parsed.wanip;
                x.lanip            = parsed.lanip;
                x.host             = parsed.host;
                x.port             = Int32.Parse(parsed.port);
                x.pending          = Convert.ToBoolean(Convert.ToInt32(a["pending"]));
                x.rdpopen          = Convert.ToBoolean(Convert.ToInt32(parsed.rdpopen));
                x.status           = parsed.status;
                x.version          = parsed.version;
                x.interval         = Int32.Parse(parsed.interval);
                x.lifetime         = Int32.Parse(parsed.lifetime);
                x.guid             = parsed.guid;
                x.servicerunning   = Boolean.Parse(parsed.servicerunning);
                x.serviceinstalled = Boolean.Parse(parsed.serviceinstalled);

                RemoteMachines.Add(x.host, x);
            }

            return(response);
        }
コード例 #26
0
 private static void DeviceLost(object sender, DeviceEventArgs args)
 {
     try
     {
         INatDevice device = args.Device;
         string     IP     = (!string.IsNullOrWhiteSpace(GlobalVars.UserConfiguration.AlternateServerIP) ? GlobalVars.UserConfiguration.AlternateServerIP : device.GetExternalIP().ToString());
         GlobalFuncs.ConsolePrint("UPnP: Device '" + IP + "' disconnected.", 3);
         StopUPnP(device, Protocol.Udp, GlobalVars.UserConfiguration.RobloxPort);
         StopUPnP(device, Protocol.Tcp, GlobalVars.UserConfiguration.RobloxPort);
         StopUPnP(device, Protocol.Udp, GlobalVars.UserConfiguration.WebServerPort);
         StopUPnP(device, Protocol.Tcp, GlobalVars.UserConfiguration.WebServerPort);
     }
     catch (Exception ex)
     {
         GlobalFuncs.ConsolePrint("UPnP: Unable to disconnect device. Reason - " + ex.Message, 2);
     }
 }
コード例 #27
0
 public static void StopUPnP(INatDevice device, Protocol protocol, int port)
 {
     if (GlobalVars.UserConfiguration.UPnP)
     {
         try
         {
             NetFuncs.StopUPnP(device, protocol, port);
             string IP = (!string.IsNullOrWhiteSpace(GlobalVars.UserConfiguration.AlternateServerIP) ? GlobalVars.UserConfiguration.AlternateServerIP : device.GetExternalIP().ToString());
             GlobalFuncs.ConsolePrint("UPnP: Port " + port + " closed on '" + IP + "' (" + protocol.ToString() + ")", 3);
         }
         catch (Exception ex)
         {
             GlobalFuncs.ConsolePrint("UPnP: Unable to close port mapping. Reason - " + ex.Message, 2);
         }
     }
 }
コード例 #28
0
        public string DiscoverPublicIpAddress()
        {
            IPAddress address = _natDevice.GetExternalIP();

            return(address.ToString());
        }
コード例 #29
0
 public void DeviceFound(object sender, DeviceEventArgs args)
 {
     try
     {
         INatDevice device = args.Device;
         string     IP     = (!string.IsNullOrWhiteSpace(GlobalVars.UserConfiguration.AlternateServerIP) ? GlobalVars.UserConfiguration.AlternateServerIP : device.GetExternalIP().ToString());
         GlobalFuncs.ConsolePrint("UPnP: Device '" + IP + "' registered.", 3, ConsoleBox);
         StartUPnP(device, Protocol.Udp, GlobalVars.UserConfiguration.RobloxPort);
         StartUPnP(device, Protocol.Tcp, GlobalVars.UserConfiguration.RobloxPort);
     }
     catch (Exception ex)
     {
         GlobalFuncs.ConsolePrint("UPnP: Unable to register device. Reason - " + ex.Message, 2, ConsoleBox);
     }
 }