Exemple #1
0
        internal void ListMappings()
        {
            if (NatMgr == null)
            {
                Server.s.Log("Initialization failed creating Windows UPnPNAT interface.");
                return;
            }

            IStaticPortMappingCollection mappings = NatMgr.StaticPortMappingCollection;

            if (mappings == null)
            {
                Server.s.Log("No mappings found. Do you have a uPnP enabled router as your gateway?");
                return;
            }

            if (mappings.Count == 0)
            {
                Server.s.Log("Router does not have any active uPnP mappings.");
            }

            foreach (IStaticPortMapping pm in mappings)
            {
                Server.s.Log("Description:");
                Server.s.Log(pm.Description);
                Server.s.Log(String.Format(" {0}:{1}  --->  {2}:{3} ({4})", pm.ExternalIPAddress, pm.ExternalPort, pm.InternalClient, pm.InternalPort, pm.Protocol));
                Server.s.Log("");
            }
        }
Exemple #2
0
        private static void OpenPort(int port)
        {
            string localIPAddress = GetLocalIPAddress();

            if (_upnpnat == null)
            {
                _upnpnat  = (UPnPNAT)Activator.CreateInstance(Type.GetTypeFromCLSID(new Guid("AE1E00AA-3FD5-403C-8A27-2BBDC30CD0E1")));
                _mappings = _upnpnat.StaticPortMappingCollection;
            }
            if (_mappings != null)
            {
                bool flag = false;
                foreach (IStaticPortMapping mapping in _mappings)
                {
                    if (mapping.InternalPort == port && mapping.InternalClient == localIPAddress && mapping.Protocol == "TCP")
                    {
                        flag = true;
                    }
                }
                if (!flag)
                {
                    _mappings.Add(port, "TCP", port, localIPAddress, bEnabled: true, "Terraria Server");
                }
            }
        }
Exemple #3
0
        internal void ClearMappings()
        {
            if (NatMgr == null)
            {
                Server.s.Log("Initialization failed creating Windows UPnPNAT interface.");
                return;
            }

            IStaticPortMappingCollection mappings = NatMgr.StaticPortMappingCollection;

            if (mappings == null)
            {
                Server.s.Log("No mappings found. Do you have a uPnP enabled router as your gateway?");
                return;
            }

            List <IStaticPortMapping> pmsToDelete = new List <IStaticPortMapping>();


            // We need to build our own list as we can not remove from mappings list without altering the list
            // resulting in last entry never being deleted.
            foreach (IStaticPortMapping pm in mappings)
            {
                pmsToDelete.Add(pm);
            }

            foreach (IStaticPortMapping pm in pmsToDelete)
            {
                Server.s.Log(String.Format("Deleting : {0}", pm.Description));
                mappings.Remove(pm.ExternalPort, pm.Protocol);
            }
        }
 public static Task <Dictionary <int, string> > GetExternalIpAndPortForTcpConnectionTask()
 {
     return(Task.Run(() =>
     {
         int port = -1;
         string extIp = string.Empty;
         var nat = new UPnPNATClass();
         IStaticPortMappingCollection portsCollection = nat.StaticPortMappingCollection;
         if (portsCollection == null)
         {
             return new Dictionary <int, string> {
                 { port, extIp }
             }
         }
         ;
         if (portsCollection.Count == 0)
         {
         }
         else
         {
             foreach (IStaticPortMapping portMapping in portsCollection)
             {
                 var iphelper = portMapping.ExternalIPAddress;
                 if (iphelper != string.Empty)
                 {
                     //iphelper;
                     break;
                 }
             }
         }
         return new Dictionary <int, string> {
             { port, extIp }
         };
     }));
 }
        public static bool GetFreePort(out int port)
        {
            port = 0;
            var set = new HashSet <int>();
            var nat = UPnPNat;
            IStaticPortMappingCollection mappings = nat.StaticPortMappingCollection;

            if (mappings == null)
            {
                return(false);
            }
            if (mappings.Count != 0)
            {
                foreach (IStaticPortMapping map in mappings)
                {
                    set.Add(map.ExternalPort);
                }
                port = FindNewPort(set);
            }
            else
            {
                port = 1;
            }

            return(true);
        }
        private static bool AddAndRemovePortForCheckingExternalIpAdress(out string ip)
        {
            var nat = UPnPNat;
            IStaticPortMappingCollection mappings = nat.StaticPortMappingCollection;
            var freeLocalPort = TcpServer.FreeTcpPort();

            ip = string.Empty;

            if (!GetFreePort(out int extPort))
            {
                return(false);
            }
            if (mappings != null)
            {
                mappings.Add(extPort, "TCP", freeLocalPort, App.GetLocalIpAddress(), true, "External IP Test");
                foreach (IStaticPortMapping map in mappings)
                {
                    ip = map.ExternalIPAddress;
                    if (ip != String.Empty)
                    {
                        mappings.Remove(extPort, "TCP");
                        return(true);
                    }
                }
            }
            return(false);
        }
Exemple #7
0
        private static void OpenPort(int port)
        {
            string localIpAddress = Netplay.GetLocalIPAddress();

            if (Netplay._upnpnat == null)
            {
                Netplay._upnpnat  = (UPnPNAT)Activator.CreateInstance(Type.GetTypeFromCLSID(new Guid("AE1E00AA-3FD5-403C-8A27-2BBDC30CD0E1")));
                Netplay._mappings = Netplay._upnpnat.StaticPortMappingCollection;
            }
            if (Netplay._mappings == null)
            {
                return;
            }
            bool flag = false;

            foreach (IStaticPortMapping mapping in Netplay._mappings)
            {
                if (mapping.InternalPort == port && mapping.InternalClient == localIpAddress && mapping.Protocol == "TCP")
                {
                    flag = true;
                }
            }
            if (flag)
            {
                return;
            }
            // ISSUE: reference to a compiler-generated method
            Netplay._mappings.Add(port, "TCP", port, localIpAddress, true, "Terraria Server");
        }
Exemple #8
0
        private void fixport_Click(object sender, EventArgs e)
        {
            UPnPNATClass upnpnat = new NATUPNPLib.UPnPNATClass();
            IStaticPortMappingCollection mappings = upnpnat.StaticPortMappingCollection;

            try
            {
                mappings.Add(Convert.ToInt32(VooblyNat), "UDP", Convert.ToInt32(VooblyNat), GetLocalIPAddress(), true, "Voobly-" + Environment.MachineName.ToString());
                ErrorClean = true;
            }
            catch (System.Runtime.InteropServices.COMException)
            {
                ErrorClean = true;
                MessageBox.Show("Already Port Forwarded!");
            }
            catch (SystemException)
            {
                ErrorClean = false;
                MessageBox.Show("Please Enable UPnP In Your Router! Then Try Again. \n If UPnP is Already Enabled That means that this functionality is broken in your router.");
            }
            finally
            {
                if (ErrorClean == true)
                {
                    checkport.Visible = true;
                    fixport.Visible   = false;
                }
            }
        }
Exemple #9
0
 private static void OpenPort()
 {
     Netplay.portForwardIP   = Netplay.GetLocalIPAddress();
     Netplay.portForwardPort = Netplay.ListenPort;
     if (Netplay.upnpnat == null)
     {
         Netplay.upnpnat  = (UPnPNAT)Activator.CreateInstance(Type.GetTypeFromCLSID(new Guid("AE1E00AA-3FD5-403C-8A27-2BBDC30CD0E1")));
         Netplay.mappings = Netplay.upnpnat.StaticPortMappingCollection;
     }
     if (Netplay.mappings == null)
     {
         return;
     }
     foreach (IStaticPortMapping mapping in Netplay.mappings)
     {
         if (mapping.InternalPort == Netplay.portForwardPort && mapping.InternalClient == Netplay.portForwardIP && mapping.Protocol == "TCP")
         {
             Netplay.portForwardOpen = true;
         }
     }
     if (Netplay.portForwardOpen)
     {
         return;
     }
     // ISSUE: reference to a compiler-generated method
     Netplay.mappings.Add(Netplay.portForwardPort, "TCP", Netplay.portForwardPort, Netplay.portForwardIP, true, "Terraria Server");
     Netplay.portForwardOpen = true;
 }
 public static Task <bool> CheckRouterCapabilities()
 {
     return(Task.Run(() =>
     {
         var nat = new UPnPNATClass();
         IStaticPortMappingCollection ports = nat.StaticPortMappingCollection;
         return ports != null;
     }));
 }
Exemple #11
0
        //const string paramExternalPort = "ext";
        //const string paramProtocol = "proto";
        //const string paramAddress = "ip";
        //const string paramPort = "port";
        //const string paramDisabled = "disabled";
        //const string paramEnabled = "enabled";
        //const string paramDescription = "desc";

        //private static void ParseParameters(string[] args)
        //{
        //    for(int i=1; i<args.Length; i++)
        //    {

        //    }
        //}

        private static IStaticPortMappingCollection retrievePortMapp0rOrExit(UPnPNAT upnpNAT)
        {
            IStaticPortMappingCollection staticMappings = upnpNAT.StaticPortMappingCollection;

            if (staticMappings == null)
            {
                FailureExit(HRESULT.S_FALSE, "Could not access static port mappings from NAT router. This can happen if it does not support UPnP, UPnP is not enabled, or its security settings disallows changes to port mappings via UPnP.");
            }
            return(staticMappings);
        }
Exemple #12
0
 private static void Init()
 {
     if (UpnpNat == null)
     {
         UpnpNat = new NATUPNPLib.UPnPNAT();
     }
     if (UpnpMap == null)
     {
         UpnpMap = UpnpNat.StaticPortMappingCollection;
     }
 }
        //This is code for get external ip
        private void NAT_TRAVERSAL_ACT()
        {
            UPnPNATClass uPnP = new UPnPNATClass();
            IStaticPortMappingCollection map = uPnP.StaticPortMappingCollection;

            foreach (IStaticPortMapping item in map)
            {
                Debug.Print(item.ExternalIPAddress);         //This line will give you external ip as string
                break;
            }
        }
Exemple #14
0
 private void DropIPV6UPNP()
 {
     foreach (string ConnectionString in ConnectionStrings)
     {
         string IPString   = ConnectionString.Substring(0, ConnectionString.LastIndexOf(":"));
         int    portStart  = ConnectionString.LastIndexOf(":") + 1;
         string portString = ConnectionString.Substring(portStart);
         if (portString.Contains("("))
         {
             portString = portString.Substring(0, portString.LastIndexOf(" ("));
         }
         int       IPV6UPNPPort = Convert.ToInt32(portString);
         IPAddress IP           = IPAddress.Parse(IPString);
         if (IP.AddressFamily == AddressFamily.InterNetworkV6)
         {
             if (!ConnectionString.EndsWith("!)"))
             {
                 UPnPNAT upnpnat = new UPnPNAT();
                 IStaticPortMappingCollection mappings = upnpnat.StaticPortMappingCollection;
                 if (IPV4ExternalIPAddress != null)
                 {
                     NetworkInterface[] Interfaces = NetworkInterface.GetAllNetworkInterfaces();
                     foreach (NetworkInterface Interface in Interfaces)
                     {
                         if (Interface.NetworkInterfaceType == NetworkInterfaceType.Wireless80211 ||
                             Interface.NetworkInterfaceType == NetworkInterfaceType.Ethernet)
                         {
                             foreach (UnicastIPAddressInformation ip in Interface.GetIPProperties().UnicastAddresses)
                             {
                                 if (ip.Address.ToString() == IP.ToString() &&
                                     Interface.GetIPProperties().GatewayAddresses.Count > 0)
                                 {
                                     GatewayIPAddressInformation Gateway = Interface.GetIPProperties().GatewayAddresses[0];
                                     if (Gateway.Address.AddressFamily == AddressFamily.InterNetworkV6)
                                     {
                                         try
                                         {
                                             mappings.Remove(IPV6UPNPPort, "TCP");
                                         }
                                         catch (System.Runtime.InteropServices.COMException ex)
                                         {
                                             MessageBox.Show(ex.Message);
                                         }
                                     }
                                 }
                             }
                         }
                     }
                 }
             }
         }
     }
 }
Exemple #15
0
 private bool DeleteMapNat(int port)
 {
     try
     {
         IStaticPortMappingCollection mappings = NatMgr.StaticPortMappingCollection;
         mappings.Remove(port, "TCP");
     }
     catch (Exception)
     {
         return(false);
     }
     return(true);
 }
Exemple #16
0
        public void StartListen(int localPort)
        {
            _packetRecieved = new AutoResetEvent(true);
            _localPort      = localPort;
            UPnPNATClass upnpnat = new UPnPNATClass();
            IStaticPortMappingCollection mappingCol = upnpnat.StaticPortMappingCollection;

            mappingCol.Add(localPort, "UDP", localPort, _localAddress.ToString(), true, "Voicer Network Client");
            Trace.WriteLine("         Added mapping to UDP port - " + localPort);
            //mappingCol.Remove(localPort, "UDP");
            _listenThread = new Thread(BeginReceive);
            _listenThread.Start();
        }
Exemple #17
0
 /// <summary>
 ///     Returns all static port mappings
 /// </summary>
 /// <remarks></remarks>
 private void GetStaticMappings()
 {
     try
     {
         _staticMapping = _upnpnat.StaticPortMappingCollection;
         if (_staticMapping == null)
         {
             _staticEnabled = false;
         }
     }
     catch (Exception)
     {
         _staticEnabled = false;
     }
 }
Exemple #18
0
        private bool SetupIPV4UPNP()
        {
            UPnPNAT upnpnat = new UPnPNAT();
            IStaticPortMappingCollection mappings = upnpnat.StaticPortMappingCollection;

            if (mappings == null)
            {
                return(false);
            }
            NetworkInterface[] Interfaces = NetworkInterface.GetAllNetworkInterfaces();
            foreach (NetworkInterface Interface in Interfaces)
            {
                if (Interface.NetworkInterfaceType == NetworkInterfaceType.Wireless80211 ||
                    Interface.NetworkInterfaceType == NetworkInterfaceType.Ethernet)
                {
                    foreach (UnicastIPAddressInformation ip in Interface.GetIPProperties().UnicastAddresses)
                    {
                        if (ip.Address.AddressFamily == AddressFamily.InterNetwork &&
                            Interface.GetIPProperties().GatewayAddresses.Count > 0)
                        {
                            foreach (GatewayIPAddressInformation thisGateway in Interface.GetIPProperties().GatewayAddresses)
                            {
                                if (thisGateway.Address.AddressFamily == AddressFamily.InterNetwork)
                                {
retry:
                                    try
                                    {
                                        mappings.Add(IPV4ExternalPort, "TCP", Port, ip.Address.ToString(), true, "Cards-IPv4");
                                        return(true);
                                    }
                                    catch (NullReferenceException)
                                    {
                                        if (IPV4ExternalPort < 60074)
                                        {
                                            IPV4ExternalPort++;
                                            goto retry;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            return(false);
        }
Exemple #19
0
        private bool SetupIPV6UPNP(IPAddress LocalIP)
        {
            int     IPV6ExternalPort = Port;
            UPnPNAT upnpnat          = new UPnPNAT();
            IStaticPortMappingCollection mappings = upnpnat.StaticPortMappingCollection;

            if (mappings == null)
            {
                return(false);
            }
            NetworkInterface[] Interfaces = NetworkInterface.GetAllNetworkInterfaces();
            foreach (NetworkInterface Interface in Interfaces)
            {
                if (Interface.NetworkInterfaceType == NetworkInterfaceType.Wireless80211 ||
                    Interface.NetworkInterfaceType == NetworkInterfaceType.Ethernet)
                {
                    foreach (UnicastIPAddressInformation ip in Interface.GetIPProperties().UnicastAddresses)
                    {
                        if (ip.Address.ToString() == LocalIP.ToString() &&
                            Interface.GetIPProperties().GatewayAddresses.Count > 0)
                        {
                            GatewayIPAddressInformation Gateway = Interface.GetIPProperties().GatewayAddresses[0];
                            if (Gateway.Address.AddressFamily == AddressFamily.InterNetworkV6)
                            {
retry:
                                try
                                {
                                    mappings.Add(IPV6ExternalPort, "TCP", Port, LocalIP.ToString(), true, "Cards-IPv6");
                                    ConnectionStrings.Add(LocalIP.ToString() + ":" + IPV6ExternalPort + " (Internet)");
                                    return(true);
                                }
                                catch (System.Runtime.InteropServices.COMException)
                                {
                                    if (IPV6ExternalPort < 60074)
                                    {
                                        IPV6ExternalPort++;
                                        goto retry;
                                    }
                                }
                            }
                        }
                    }
                }
            }
            return(false);
        }
 public static void DisplayallPorts()
 {
     try
     {
         var nat = UPnPNat;
         IStaticPortMappingCollection mappings = nat.StaticPortMappingCollection;
         MessageBox.Show("Count: " + mappings.Count);
         foreach (IStaticPortMapping mapping in mappings)
         {
             //Console.WriteLine(mapping.);
         }
     }
     catch (Exception)
     {
         MessageBox.Show("Your router doesn't support this.");
     }
 }
Exemple #21
0
        public Task <PortResult> ClosePort(UPnPPort port)
        {
            return(Task <PortResult> .Run(async() =>
            {
                switch (State)
                {
                case UPnPSupportState.Supported:
                    try
                    {
                        List <UPnPPort> ports = await getOpenedPorts();

                        if (!ports.Contains(port))
                        {
                            return PortResult.AlreadyClosed;
                        }

                        IStaticPortMappingCollection maps = manager.StaticPortMappingCollection;
                        foreach (IStaticPortMapping map in maps)
                        {
                            UPnPPort port2 = convert(map);
                            if (port == port2)
                            {
                                maps.Remove(map.ExternalPort, map.Protocol);
                                return PortResult.Closed;
                            }
                        }
                        return PortResult.FailedUnknown;
                    }
                    catch (Exception)
                    {
                        return PortResult.FailedUnknown;
                    }

                case UPnPSupportState.NotSupported:
                    return PortResult.EngineNotSupported;

                case UPnPSupportState.NoPrepared:
                    return PortResult.EngineNotPrepared;

                default:
                    break;
                }

                return PortResult.FailedUnknown;
            }));
        }
        public bool InitAndFindRouter()
        {
            try
            {
                upnpnat = new UPnPNAT();
                mappings = upnpnat.StaticPortMappingCollection;

                if (mappings != null)
                    return true;
                else
                    return false;
            }
            catch
            {
                return false;
            }
        }
Exemple #23
0
        internal bool AddMapping(ushort Port, string Protocol, string Description)
        {
            if (NatMgr == null)
            {
                Server.s.Log("Initialization failed creating Windows UPnPNAT interface.");
                return(false);
            }

            IStaticPortMappingCollection mappings = NatMgr.StaticPortMappingCollection;

            if (mappings == null)
            {
                Server.s.Log("No mappings found. Do you have a uPnP enabled router as your gateway?");
                return(false);
            }

            mappings.Add(Port, Protocol, Port, GetLocalIP(), true, Description);
            return(true);
        }
Exemple #24
0
        //const string paramExternalPort = "ext";
        //const string paramProtocol = "proto";
        //const string paramAddress = "ip";
        //const string paramPort = "port";
        //const string paramDisabled = "disabled";
        //const string paramEnabled = "enabled";
        //const string paramDescription = "desc";

        //private static void ParseParameters(string[] args)
        //{
        //    for(int i=1; i<args.Length; i++)
        //    {

        //    }
        //}

        private static void ListMappings(UPnPNAT upnpNAT, string[] args)
        {
            if (args.Length > 1)
            {
                FailureExit(HRESULT.E_INVALIDARG, "Parameters not yet implemented.");
            }

            IStaticPortMappingCollection staticMappings = upnpNAT.StaticPortMappingCollection;

            if (staticMappings == null)
            {
                FailureExit(HRESULT.S_FALSE, "Could not retrieve static port mappings from NAT router. This can happen if it does not support UPnP (or it is not enabled).");
            }

            Console.Write("Found " + staticMappings.Count + " port mappings");
            if (staticMappings.Count > 0)
            {
                Console.WriteLine(":");
                Console.WriteLine();

                PrintPortMappingHeader();

                IEnumerator enumerat0r = staticMappings.GetEnumerator();
                while (enumerat0r.MoveNext())
                {
                    IStaticPortMapping portMapping = enumerat0r.Current as IStaticPortMapping;
                    if (portMapping == null)
                    {
                        FailureExit(HRESULT.E_UNEXPECTED, "The port mappings just got updated or changed otherwise. Please run me again to get the current results.");
                    }

                    PrintPortMapping(portMapping);
                }

                PrintPortMappingFooter();
            }
            else
            {
                Console.WriteLine(".");
            }

            Console.WriteLine();
        }
        public static bool OpenNewPortForUpnp(out int port)
        {
            port = 0;
            if (!GetFreePort(out port))
            {
                return(false);
            }

            var upnp = UPnPNat;
            IStaticPortMappingCollection mappings = upnp.StaticPortMappingCollection;

            if (mappings == null)
            {
                return(false);
            }

            mappings.Add(port, "TCP", App.TcpPort, App.GetLocalIpAddress(), true, "Lazy Steam Helper communication port");
            return(true);
        }
Exemple #26
0
        public bool InitAndFindRouter()
        {
            try
            {
                upnpnat  = new UPnPNAT();
                mappings = upnpnat.StaticPortMappingCollection;

                if (mappings != null)
                {
                    return(true);
                }
                else
                {
                    return(false);
                }
            }
            catch
            {
                return(false);
            }
        }
Exemple #27
0
        private void UpdatePortForwards()
        {
            lblPortStatus.Text = "Checking port forwards...";
            try
            {
                tblPortForwards.Rows.Clear();
                IPAddress externalIP = YAMS.Networking.GetExternalIP();
                lblExternalIP.Text = externalIP.ToString();

                UPnPNATClass upnpnat = new UPnPNATClass();
                IStaticPortMappingCollection mappings = upnpnat.StaticPortMappingCollection;

                progToolStrip.Maximum = mappings.Count;

                foreach (IStaticPortMapping p in mappings)
                {
                    //This lists all available port mappings on the device, which could be an awful lot
                    if (p.Description.IndexOf("YAMS") > -1)
                    {
                        //Check the port is open
                        bool portOpen = YAMS.Networking.CheckExternalPort(externalIP, p.ExternalPort);

                        //Add the port forward to the table
                        DataGridViewRow row = new DataGridViewRow();
                        row.CreateCells(tblPortForwards);
                        row.Cells[0].Value = p.Description;
                        row.Cells[1].Value = p.ExternalPort;
                        row.Cells[2].Value = portOpen;
                        tblPortForwards.Rows.Add(row);
                    }
                    progToolStrip.PerformStep();
                }
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }
            lblPortStatus.Text = "Done";
        }
Exemple #28
0
        /// <summary>Removes virus-like "Teredo" mappings which Windows 7 tends to fill up the map table with.</summary>
        /// <remarks>If you don't do this, the UPnP mapping table will always be full and the attempted mapping will always fail.</remarks>
        private static void DeleteTeredoMappings(IStaticPortMappingCollection mappings)
        {
            if (mappings == null)
            {
                return;
            }

            List <IStaticPortMapping> teredoMappings = new List <IStaticPortMapping>();

            foreach (IStaticPortMapping mapping in mappings)
            {
                if (mapping.Description.ToLower().Contains("teredo"))
                {
                    teredoMappings.Add(mapping);
                }
            }

            foreach (IStaticPortMapping mapping in teredoMappings)
            {
                mappings.Remove(mapping.ExternalPort, mapping.Protocol);
            }
        }
Exemple #29
0
        private void DropIPV4UPNP()
        {
            UPnPNAT upnpnat = new UPnPNAT();
            IStaticPortMappingCollection mappings = upnpnat.StaticPortMappingCollection;

            if (IPV4ExternalIPAddress != null)
            {
                NetworkInterface[] Interfaces = NetworkInterface.GetAllNetworkInterfaces();
                foreach (NetworkInterface Interface in Interfaces)
                {
                    if (Interface.NetworkInterfaceType == NetworkInterfaceType.Wireless80211 ||
                        Interface.NetworkInterfaceType == NetworkInterfaceType.Ethernet)
                    {
                        foreach (UnicastIPAddressInformation ip in Interface.GetIPProperties().UnicastAddresses)
                        {
                            if (ip.Address.AddressFamily == AddressFamily.InterNetwork &&
                                Interface.GetIPProperties().GatewayAddresses.Count > 0)
                            {
                                GatewayIPAddressInformation Gateway = Interface.GetIPProperties().GatewayAddresses[0];
                                if (Gateway.Address.AddressFamily == AddressFamily.InterNetwork)
                                {
                                    try
                                    {
                                        mappings.Remove(IPV4ExternalPort, "TCP");
                                    }
                                    catch (System.Runtime.InteropServices.COMException ex)
                                    {
                                        MessageBox.Show(ex.Message);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        public static bool GetExternalIpAdress(out string ip)
        {
            ip = string.Empty;
            var nat = UPnPNat;
            IStaticPortMappingCollection mappings = nat.StaticPortMappingCollection;

            if (mappings != null)
            {
                if (mappings.Count != 0)
                {
                    foreach (IStaticPortMapping map in mappings)
                    {
                        ip = map.ExternalIPAddress;
                        if (ip != String.Empty)
                        {
                            return(true);
                        }
                    }
                }
                var success = AddAndRemovePortForCheckingExternalIpAdress(out ip);
                return(success);
            }
            return(false);
        }
Exemple #31
0
        static void Main(string[] args)
        {
            if (args.Length == 0)
            {
                Console.WriteLine("Error: No arguments given.");
                return;
            }

            Console.WriteLine("Welcome to UPnP Helper by Floris de Haan.");
            Console.WriteLine("Loading...");

            // Connect to UPnP
            UPNP_CONN = new UPnPNATClass();
            PORT_MAPPING = UPNP_CONN.StaticPortMappingCollection;

            if (PORT_MAPPING == null)
            {
                Console.WriteLine("Error: Failed to load UPnP.");
                return;
            }

            Console.WriteLine("UPnP has been loaded succesfully.");

            // Get app task
            int port, maxPort;
            string desc, client, proto;

            switch (args[0])
            {
                // bind [PROTO] [MIN_PORT] [MAX_PORT] [CLIENT] [DESC]
                case "bind":
                    if (args.Length != 6)
                    {
                        Console.WriteLine("Error: Argument mismatch. use: bind [PROTO] [MIN_PORT] [MAX_PORT] [CLIENT] [DESC]");
                        return;
                    }

                    if (!Int32.TryParse(args[2], out port) || !Int32.TryParse(args[3], out maxPort))
                    {
                        Console.WriteLine("Error: Failed to parse port.");
                        return;
                    }

                    proto = args[1];
                    client = args[4];
                    desc = args[5];

                    // Check if port is used
                    while (true)
                    {
                        try
                        {
                            IStaticPortMapping item = PORT_MAPPING[port, proto];
                            if (item.InternalClient == client)
                            {
                                //Console.WriteLine("Error: Port {0} is already assigned to self.");
                                Console.WriteLine("Succeed. At port " + port.ToString());
                                return;
                            }
                            else
                            {
                                Console.WriteLine("Error: Port {0} is already used by other client.");
                                port++;
                                if (port > maxPort)
                                    return;
                            }
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine("Port is avaiable.");
                            break;
                        }
                    }

                    // Add Port
                    try
                    {
                        PORT_MAPPING.Add(port, proto, port, client, true, desc);
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("Error: " + e.ToString());
                        return;
                    }

                    Console.WriteLine("Succeed. At port " + port.ToString());

                    break;
                // unbind [PROTO] [EXTERN_PORT]
                case "unbind":
                    if (args.Length != 3)
                    {
                        Console.WriteLine("Error: Argument mismatch. use: unbind [PROTO] [EXTERN_PORT]");
                        return;
                    }

                    proto = args[1];

                    if (!Int32.TryParse(args[2], out port))
                    {
                        Console.WriteLine("Error: Failed to parse port.");
                        return;
                    }

                    try
                    {
                        PORT_MAPPING.Remove(port, proto);
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("Error: " + e.ToString());
                        return;
                    }

                    Console.WriteLine("Succeed. At port " + port.ToString());

                    break;
                default:
                    Console.WriteLine("Unknown command.");
                    break;
            }
        }
Exemple #32
0
        public void ConnectOrDisconnect()
        {
            if (TCPClient.Connected)
            {
                TCPClient.Client.Disconnect(true);

                UDPListen = false;
                TCPListen = false;
                Clients.Clear();

                if (UPnPEnabled)
                    ClearUpUPnP();

                if (OnServerDisconnect != null)
                    OnServerDisconnect.Invoke(this, new EventArgs());

                if (OnResultsUpdate != null)
                    OnResultsUpdate.Invoke(this, "Disconnected.");
            }
            else
            {
                try
                {
                    InternetAccessAdapter = GetAdapterWithInternetAccess();

                    if (OnResultsUpdate != null)
                        OnResultsUpdate.Invoke(this, "Adapter with Internet Access: " + InternetAccessAdapter);

                    TCPClient = new TcpClient();
                    TCPClient.Client.Connect(ServerEndpoint);

                    UDPListen = true;
                    TCPListen = true;

                    SendMessageUDP(LocalClientInfo.Simplified(), ServerEndpoint);
                    LocalClientInfo.InternalEndpoint = (IPEndPoint)UDPClient.Client.LocalEndPoint;

                    if (UPnPEnabled)
                    {
                        UPnPMappings = UPnPNAT.StaticPortMappingCollection;
                        ClearUpUPnP();

                        if (LocalClientInfo.InternalEndpoint != null)
                        {
                            if (OnResultsUpdate != null)
                                OnResultsUpdate.Invoke(this, "UDP Listening on Port " + LocalClientInfo.InternalEndpoint.Port);

                            if (AttemptUPnP(LocalClientInfo.InternalEndpoint.Port))
                            {
                                if (OnResultsUpdate != null)
                                    OnResultsUpdate.Invoke(this, "UPnP Map Added");

                                LocalClientInfo.UPnPEnabled = true;
                            }
                            else
                            {
                                if (OnResultsUpdate != null)
                                    OnResultsUpdate.Invoke(this, "UPnP Mapping Not Possible");
                            }
                        }
                    }

                    Thread.Sleep(500);
                    SendMessageTCP(LocalClientInfo);

                    Thread KeepAlive = new Thread(new ThreadStart(delegate
                    {
                        while (TCPClient.Connected)
                        {
                            Thread.Sleep(5000);
                            SendMessageTCP(new KeepAlive());
                        }
                    }));

                    KeepAlive.IsBackground = true;
                    KeepAlive.Start();

                    if (OnServerConnect != null)
                        OnServerConnect.Invoke(this, new EventArgs());

                }
                catch (Exception ex)
                {
                    if (OnResultsUpdate != null)
                        OnResultsUpdate.Invoke(this, "Error when connecting " + ex.Message);
                }
            }
        }
Exemple #33
0
 /// <summary>
 ///     Returns all static port mappings
 /// </summary>
 /// <remarks></remarks>
 private void GetStaticMappings()
 {
     try
     {
         _staticMapping = _upnpnat.StaticPortMappingCollection;
         if (_staticMapping == null) _staticEnabled = false;
     }
     catch (Exception)
     {
         _staticEnabled = false;
     }
 }
Exemple #34
0
        public void ConnectOrDisconnect()
        {
            if (TCPClient.Connected)
            {
                TCPClient.Client.Disconnect(true);

                UDPListen = false;
                TCPListen = false;
                Clients.Clear();

                if (UPnPEnabled)
                {
                    ClearUpUPnP();
                }

                if (OnServerDisconnect != null)
                {
                    OnServerDisconnect.Invoke(this, new EventArgs());
                }

                if (OnResultsUpdate != null)
                {
                    OnResultsUpdate.Invoke(this, "Disconnected.");
                }
            }
            else
            {
                try
                {
                    InternetAccessAdapter = GetAdapterWithInternetAccess();

                    if (OnResultsUpdate != null)
                    {
                        OnResultsUpdate.Invoke(this, "Adapter with Internet Access: " + InternetAccessAdapter);
                    }

                    TCPClient = new TcpClient();
                    TCPClient.Client.Connect(ServerEndpoint);

                    UDPListen = true;
                    TCPListen = true;

                    SendMessageUDP(LocalClientInfo.Simplified(), ServerEndpoint);
                    LocalClientInfo.InternalEndpoint = (IPEndPoint)UDPClient.Client.LocalEndPoint;

                    if (UPnPEnabled)
                    {
                        UPnPMappings = UPnPNAT.StaticPortMappingCollection;
                        ClearUpUPnP();

                        if (LocalClientInfo.InternalEndpoint != null)
                        {
                            if (OnResultsUpdate != null)
                            {
                                OnResultsUpdate.Invoke(this, "UDP Listening on Port " + LocalClientInfo.InternalEndpoint.Port);
                            }

                            if (AttemptUPnP(LocalClientInfo.InternalEndpoint.Port))
                            {
                                if (OnResultsUpdate != null)
                                {
                                    OnResultsUpdate.Invoke(this, "UPnP Map Added");
                                }

                                LocalClientInfo.UPnPEnabled = true;
                            }
                            else
                            {
                                if (OnResultsUpdate != null)
                                {
                                    OnResultsUpdate.Invoke(this, "UPnP Mapping Not Possible");
                                }
                            }
                        }
                    }

                    Thread.Sleep(500);
                    SendMessageTCP(LocalClientInfo);

                    Thread KeepAlive = new Thread(new ThreadStart(delegate
                    {
                        while (TCPClient.Connected)
                        {
                            Thread.Sleep(5000);
                            SendMessageTCP(new KeepAlive());
                        }
                    }));

                    KeepAlive.IsBackground = true;
                    KeepAlive.Start();

                    if (OnServerConnect != null)
                    {
                        OnServerConnect.Invoke(this, new EventArgs());
                    }
                }
                catch (Exception ex)
                {
                    if (OnResultsUpdate != null)
                    {
                        OnResultsUpdate.Invoke(this, "Error when connecting " + ex.Message);
                    }
                }
            }
        }