예제 #1
0
 public static void RemoveUPNPServer(int ServerPort, int QueryPort)
 {
     if (UpnpMap == null)
     {
         return;
     }
     UpnpMap.Remove(ServerPort, "UDP");
     UpnpMap.Remove(QueryPort, "UDP");
 }
예제 #2
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);
            }
        }
예제 #3
0
        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);
        }
예제 #4
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);
            }
        }
예제 #5
0
 public static void closePort()
 {
     if (portForwardOpen)
     {
         mappings.Remove(portForwardPort, "TCP");
     }
 }
예제 #6
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);
                                         }
                                     }
                                 }
                             }
                         }
                     }
                 }
             }
         }
     }
 }
예제 #7
0
 public static bool closePort()
 {
     try
     {
         if (portForwardOpen)
         {
             mappings.Remove(portForwardPort, "TCP");
         }
         return(true);
     }
     catch { }
     return(false);
 }
예제 #8
0
 private bool DeleteMapNat(int port)
 {
     try
     {
         IStaticPortMappingCollection mappings = NatMgr.StaticPortMappingCollection;
         mappings.Remove(port, "TCP");
     }
     catch (Exception)
     {
         return(false);
     }
     return(true);
 }
예제 #9
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;
            }));
        }
예제 #10
0
        public void ClearUpUPnP()
        {
            if (UPnPMappings != null)
            {
                List <int> PortMappingsToDelete = new List <int>();

                foreach (IStaticPortMapping map in UPnPMappings)
                {
                    try
                    {
                        //if (map.Protocol == "UDP" && map.Description == "P2P Chat" && map.InternalClient == InternetAccessAdapter.ToString())
                        //    PortMappingsToDelete.Add(map.ExternalPort);
                        if (map.Protocol == "UDP" && map.Description == "DataDepositer P2P" &&
                            map.InternalClient == InternetAccessAdapter.ToString())
                        {
                            PortMappingsToDelete.Add(map.ExternalPort);
                        }
                    }
                    catch
                    {
                    }
                }

                foreach (int port in PortMappingsToDelete)
                {
                    try
                    {
                        UPnPMappings.Remove(port, "UDP");

                        if (OnResultsUpdate != null)
                        {
                            OnResultsUpdate.Invoke(this, "UPnP Map " + port + " Removed");
                        }
                    }
                    catch (Exception ex)
                    {
                        if (OnResultsUpdate != null)
                        {
                            OnResultsUpdate.Invoke(this, "Failed to remove UPnP Map " + port + ": " + ex.Message);
                        }
                    }
                }
            }
        }
예제 #11
0
        private static void ClosePort(int port)
        {
            string localIPAddress = GetLocalIPAddress();
            bool   flag           = false;

            if (_mappings != null)
            {
                foreach (IStaticPortMapping mapping in _mappings)
                {
                    if (mapping.InternalPort == port && mapping.InternalClient == localIPAddress && mapping.Protocol == "TCP")
                    {
                        flag = true;
                    }
                }
                if (!flag)
                {
                    _mappings.Remove(port, "TCP");
                }
            }
        }
예제 #12
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);
            }
        }
예제 #13
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);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
예제 #14
0
 public static void RemovePortForward(int Port)
 {
     MappingCollection.Remove(Port, "TCP");
 }
예제 #15
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;
            }
        }
예제 #16
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);
            }
        }