Exemple #1
0
        public static void Makeport(int _Iport, int _Eport)
        {
            PRT  = _Iport;
            EPRT = _Eport;

            foreach (var ip in IIP)
            {
                if (ip.ToString().Contains("192.168.1"))
                {
                    IIPS = ip;
                    Console.Beep();
                }
            }


            if (UPNP == null)
            {
                Console.WriteLine("Initialization failed creating Windows UPnPNAT interface.");
                return;
            }

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

            if (map.Count == 0)
            {
                Ismapempty = true;
            }
            else
            {
                Ismapempty = false;
            }

            if (Ismapempty)
            {
                map.Add(EPRT, PROTOCOL, PRT, IIPS, true, SNAME);
                Console.WriteLine("The local port " + _Iport + " is being port forwarded to " + _Eport + " from internal ip " + IIPS + ". Use canyouseeme.org to find the port is forwarded");
                Console.Beep(2, 1);
            }
            else
            {
                map.Remove(EPRT, PROTOCOL);
                map.Add(EPRT, PROTOCOL, PRT, IIPS, true, SNAME);
                Console.WriteLine("The local port " + _Iport + " is being port forwarded to " + _Eport + " from internal ip " + IIPS + ". Use canyouseeme.org to find the port is forwarded");
                Console.Beep(4, 1);
            }
        }
        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 #3
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;
                }
            }
        }
 public static bool openPort()
 {
     portForwardIP   = Netplay.ServerIPText;          // .LocalIPAddress();
     portForwardPort = Netplay.ListenPort;
     if (mappings == null)
     {
         Console.WriteLine("(UPnP) Your UPnP discovery is down.");
         TShock.Log.Info("(UPnP) Your UPnP discovery is down.");
         return(false);
     }
     try
     {
         foreach (IStaticPortMapping staticPortMapping in mappings)
         {
             if (staticPortMapping.InternalPort == portForwardPort && staticPortMapping.InternalClient == portForwardIP && staticPortMapping.Protocol == "TCP")
             {
                 portForwardOpen = true;
             }
         }
         if (!portForwardOpen)
         {
             mappings.Add(portForwardPort, "TCP", portForwardPort, portForwardIP, true, "Terraria Server");
             portForwardOpen = true;
         }
         return(true);
     }
     catch { }
     return(false);
 }
Exemple #5
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 #6
0
 public static bool AddUPNPServer(int ServerPort, int QueryPort, string AltSaveDir)
 {
     Init();
     if (UpnpMap == null)
     {
         AtlasServerManager.GetInstance().Log("[Auto Port Forwarding] UPNP Does not seeem enabled at the router admins interface");
         return(false);
     }
     foreach (IStaticPortMapping EMaps in UpnpMap)
     {
         if (EMaps.ExternalPort == ServerPort || EMaps.ExternalPort == QueryPort)
         {
             return(false);
         }
     }
     UpnpMap.Add(ServerPort, "UDP", ServerPort, LocalIPAddress, true, "Atlas Server: " + AltSaveDir);
     UpnpMap.Add(QueryPort, "UDP", QueryPort, LocalIPAddress, true, "Atlas Query: " + AltSaveDir);
     return(true);
 }
        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 #8
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 #9
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);
        }
Exemple #10
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 #11
0
 private bool AttemptUPnP(int Port)
 {
     if (UPnPMappings == null)
     {
         return(false);
     }
     else
     {
         try
         {
             UPnPMappings.Add(Port, "UDP", Port, InternetAccessAdapter.ToString(), true, "P2P Chat");
             return(true);
         }
         catch
         {
             return(false);
         }
     }
 }
        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 #13
0
 private static void OpenPort()
 {
     portForwardIP   = GetLocalIPAddress();
     portForwardPort = ListenPort;
     if (mappings != null)
     {
         foreach (IStaticPortMapping mapping in mappings)
         {
             if (mapping.InternalPort == portForwardPort && mapping.InternalClient == portForwardIP && mapping.Protocol == "TCP")
             {
                 portForwardOpen = true;
             }
         }
         if (!portForwardOpen)
         {
             mappings.Add(portForwardPort, "TCP", portForwardPort, portForwardIP, true, "Terraria Server");
             portForwardOpen = true;
         }
     }
 }
Exemple #14
0
        /// <summary>
        ///     Adds a port mapping to the UPnP enabled device.
        /// </summary>
        /// <param name="localIp">The local IP address to map to.</param>
        /// <param name="port">The port to forward.</param>
        /// <param name="protocol">The protocol of the port [TCP/UDP]</param>
        /// <param name="desc">A small description of the port.</param>
        /// <exception cref="ApplicationException">This exception is thrown when UPnP is disabled.</exception>
        /// <exception cref="ObjectDisposedException">This exception is thrown when this class has been disposed.</exception>
        /// <exception cref="ArgumentException">This exception is thrown when any of the supplied arguments are invalid.</exception>
        /// <remarks></remarks>
        private void Add(string localIp, uint port, Protocol protocol, string desc)
        {
            // Begin utilizing
            if (Exists(port, protocol))
            {
                throw new ArgumentException("This mapping aLocale.Tready exists!", port + " : " + protocol);
            }

            // Check
            if (!IsPrivateIp(localIp))
            {
                throw new ArgumentException("This is not a local IP address!", "localIp");
            }

            // Final check!
            if (!_staticEnabled)
            {
                throw new ApplicationException("UPnP is not enabled, or there was an error with UPnP Initialization.");
            }

            // Okay, continue on
            _staticMapping.Add(Convert.ToInt32(port), protocol.ToString(), Convert.ToInt32(port), localIp, true, desc);
        }
Exemple #15
0
        private async void createHost(string hostIP)
        {
            var testNetIp = "";

            try { testNetIp = getLocalIp(); } catch (Exception) { }
            //Check Network Connection First Of All
            if (isNetworkAvailable() || (testNetIp != "127.0.0.1" && testNetIp != ""))
            {
                #region Try To Open Port 8888
                try
                {
                    bool isPortOpened = false;
                    try
                    {
                        #region Create Port Mapping Via UPnP Native Lib
                        //create port mapping via UPnP
                        UPnPNATClass upnpnat = new UPnPNATClass();
                        IStaticPortMappingCollection mappings = upnpnat.StaticPortMappingCollection;
                        foreach (IStaticPortMapping portMapping in mappings)
                        {
                            // remove any old mappings
                            if (portMapping.ExternalPort == 8888)
                            {
                                // Remove TCP forwarding for Port 8888
                                mappings.Remove(8888, "TCP");
                                // Remove UDP forwarding for Port 8888
                                mappings.Remove(8888, "UDP");
                            }
                        }
                        // Add TCP forwarding for Port 8888
                        mappings.Add(8888, "TCP", 8888, getLocalIp(), true, "MGS");
                        // Add UDP forwarding for Port 8888
                        mappings.Add(8888, "UDP", 8888, getLocalIp(), true, "MGS");
                        isPortOpened = true;
                        #endregion
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                        isPortOpened = false;
                    }
                    if (!isPortOpened)
                    {
                        #region Create Port Mapping Via UPnP Open.NAT Lib
                        var discoverer = new NatDiscoverer();
                        var cts        = new CancellationTokenSource(10000);
                        var device     = await discoverer.DiscoverDeviceAsync(PortMapper.Upnp, cts);

                        // remove any old mappings
                        foreach (var mapping in await device.GetAllMappingsAsync())
                        {
                            if (mapping.Description.Contains("MGS"))
                            {
                                await device.DeletePortMapAsync(mapping);
                            }
                        }
                        // Add TCP forwarding for Port 8888
                        await device.CreatePortMapAsync(new Mapping(Protocol.Tcp, IPAddress.Parse(getLocalIp()), 8888, 8888, 0, "MGS"));

                        // Add UDP forwarding for Port 8888
                        await device.CreatePortMapAsync(new Mapping(Protocol.Udp, IPAddress.Parse(getLocalIp()), 8888, 8888, 0, "MGS"));

                        isPortOpened = true;
                        #endregion
                    }
                }
                catch (Exception)
                {
                    MessageBox.Show("It seems to be that your router does not support UPnP!\n"
                                    + "Please open the port < 8888 (TCP/UDP) > manually then press ok", "Cannot Open <8888> Port Automatically :(",
                                    MessageBoxButton.OK, MessageBoxImage.Exclamation);
                }
                #endregion

                //Open Host And Join Self
                try
                {
                    //get host.exe path
                    string hostPath = System.Reflection.Assembly.GetEntryAssembly().Location;
                    hostPath = hostPath.Replace("Client", "Host");
                    //set Host IP
                    globalVars.userIp = hostIP;
                    //start server
                    System.Diagnostics.Process.Start(hostPath, globalVars.userIp);
                    //join self
                    await Task.Run(() => { joinSelf(); });
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                    resetGraphics();
                    return;
                }
                //Open Room In Database And Join It then Switch Window
                try
                {
                    //Initialize And Create A GameRoom
                    this.Dispatcher.Invoke((Action)(() => { initAndCreateGameRoom(); }));
                    //Join The Game Room
                    if (globalVars.roomId != 0)
                    {
                        bool isJoined = globalVars.proxy.joinRoom(globalVars.roomId,
                                                                  globalVars.player.id, globalVars.userIp);
                        if (isJoined)
                        {
                            Application.Current.Dispatcher.Invoke((Action) delegate
                            {
                                switchToNextWindow();
                            });
                        }
                        else
                        {
                            //Try To Delete The Room
                            try
                            {
                                globalVars.proxy.deleteRoom();
                            }
                            catch (Exception) //If The Server Failed To Delete The Room (Connection Lost)
                            {
                                globalVars.offlineGameController.deleteRoom(globalVars.roomId);
                            }
                            MessageBox.Show("Room Created But Cannot Join The Room!", "Internal Error Occured :(",
                                            MessageBoxButton.OK, MessageBoxImage.Error);
                            resetGraphics();
                            return;
                        }
                    }
                    else
                    {
                        resetGraphics();
                        return;
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                    resetGraphics();
                    return;
                }
            }
            else
            {
                MessageBox.Show("Please Check Your Network Connection!", "Network Connection Missing.",
                                MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
Exemple #16
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 #17
0
        public Task <PortResult> OpenPort(UPnPPort port)
        {
            return(Task <PortResult> .Run(async() =>
            {
                try
                {
                    switch (State)
                    {
                    case UPnPSupportState.Supported:

                        try
                        {
                            List <UPnPPort> ports = await getOpenedPorts();

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

                            IStaticPortMappingCollection maps = manager.StaticPortMappingCollection;
                            switch (port.Type)
                            {
                            case PortType.TCP:
                                maps.Add(port.ExternalPort, "TCP", port.InternalPort, port.InternalAddress, true, port.Description);
                                break;

                            case PortType.UDP:
                                maps.Add(port.ExternalPort, "UDP", port.InternalPort, port.InternalAddress, true, port.Description);
                                break;

                            case PortType.BOTH:
                                maps.Add(port.ExternalPort, "TCP", port.InternalPort, port.InternalAddress, true, port.Description);
                                maps.Add(port.ExternalPort, "UDP", port.InternalPort, port.InternalAddress, true, port.Description);
                                break;

                            default:
                                break;
                            }
                            return PortResult.Opened;
                        }
                        catch (Exception)
                        {
                            return PortResult.FailedUnknown;
                        }

                    case UPnPSupportState.NotSupported:
                        return PortResult.EngineNotSupported;

                    case UPnPSupportState.NoPrepared:
                        return PortResult.EngineNotPrepared;

                    default:
                        return PortResult.FailedUnknown;
                    }
                }
                catch (Exception)
                {
                    return PortResult.FailedUnknown;
                }
            }));
        }
Exemple #18
0
 public static void AddPortForward(int Port, string IP)
 {
     MappingCollection.Add(Port, "TCP", Port, IP, true, "Imperium Remote Administration Tool");
 }