示例#1
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;
 }
示例#2
0
文件: UPnP.cs 项目: nhz2f/xRAT
        public static void ForwardPort(ushort port)
        {
            new Thread(() =>
            {
                EndPoint endPoint;
                string ipAddr = "";
                int i = 0;

            Retry:
                try
                {
                    TcpClient c = new TcpClient();
                    c.Connect("www.google.com", 80);
                    endPoint = c.Client.LocalEndPoint;
                    c.Close();

                    if (endPoint != null)
                    {
                        ipAddr = endPoint.ToString();
                        int index = ipAddr.IndexOf(":");
                        ipAddr = ipAddr.Remove(index);
                    }
                }
                catch { i++; if (i < 5) goto Retry; }

                try
                {
                    IStaticPortMappingCollection portMap = new UPnPNAT().StaticPortMappingCollection;
                    if (portMap != null)
                        portMap.Add(port, "TCP", port, ipAddr, true, "xRAT 2.0 UPnP");
                }
                catch
                { }
            }).Start();
        }
示例#3
0
        private static void AddMapping(UPnPNAT upnpNAT, string[] args)
        {
            //	     <port> <protocol> <mapped-address> [mapped-port]"

            if (args.Length < 1 + 3)
            {
                // PrintAddMappingUsage()
                FailureExit(HRESULT.E_INVALIDARG, "You need to specifiy at least the port, protocol and mapped address.");
            }

            //ParseParameters(args);

            int port;

            if (!int.TryParse(args[1], out port) || port < 0 || port > 65536)
            {
                FailureExit(HRESULT.E_INVALIDARG, "The specified port is invalid");
            }

            string protocol = args[2].ToUpperInvariant();

            if (protocol != "TCP" && protocol != "UDP")
            {
                FailureExit(HRESULT.E_INVALIDARG, "The specified protocol is invalid");
            }

            string internalAddress = args[3];

            // CHECK IP 6+4

            int internalPort;

            if (args.Length > 1 + 3)
            {
                if (!int.TryParse(args[4], out internalPort) || internalPort < 0 || internalPort > 65536)
                {
                    FailureExit(HRESULT.E_INVALIDARG, "The specified mapped-port is invalid");
                }
            }
            else
            {
                internalPort = port;
            }

            try
            {
//				var peter = upnpNAT.DynamicPortMappingCollection.Count;


                var peter2 = upnpNAT.StaticPortMappingCollection.Count;

                upnpNAT.StaticPortMappingCollection.Add(port, protocol, internalPort, internalAddress, true, "UPnP_PortMapp0r");                // "UPnP_PortMapp0r @ ");
                //upnpNAT.StaticPortMappingCollection.Add(port, protocol, internalPort, internalAddress, true, "UPnP_PortMapp0r @ " + DateTime.Now);
            }
            catch (Exception exception)
            {
                Console.WriteLine(exception.InnerException);
                FailureExit(HRESULT.S_FALSE, "Could not add port mapping. Exception: " + exception.Message);
            }
        }
示例#4
0
        private static void RemoveMapping(UPnPNAT upnpNAT, string[] args)
        {
            if (args.Length < 1 + 2)
            {
                FailureExit(HRESULT.E_INVALIDARG, "You need to specifiy the port and protocol.");
            }

            int port;

            if (!int.TryParse(args[1], out port) || port < 0 || port > 65536)
            {
                FailureExit(HRESULT.E_INVALIDARG, "The specified port is invalid");
            }

            string protocol = args[2].ToUpperInvariant();

            if (protocol != "TCP" && protocol != "UDP")
            {
                FailureExit(HRESULT.E_INVALIDARG, "The specified protocol is invalid");
            }

            try
            {
                upnpNAT.StaticPortMappingCollection.Remove(port, protocol);
            }
            catch (System.IO.FileNotFoundException exc)
            {
                FailureExit(HRESULT.S_FALSE, "The specified port mapping does not exist.");                      // TODO: just return success then?
            }
        }
示例#5
0
文件: UPnP.cs 项目: master2be1/xRAT
        public static void ForwardPort(ushort port)
        {
            new Thread(() =>
            {
                EndPoint endPoint;
                string ipAddr = "";
                int retry     = 0;

                do
                {
                    try
                    {
                        TcpClient c = null;
                        try
                        {
                            c = new TcpClient();
                            c.Connect("www.google.com", 80);
                            endPoint = c.Client.LocalEndPoint;
                        }
                        finally
                        {
                            // Placed in here to make sure that a failed TcpClient will never linger!
                            if (c != null)
                            {
                                c.Close();
                            }
                        }

                        if (endPoint != null)
                        {
                            ipAddr    = endPoint.ToString();
                            int index = ipAddr.IndexOf(":");
                            ipAddr    = ipAddr.Remove(index);
                        }
                        // We got through successfully. We may exit the loop.
                        break;
                    }
                    catch
                    {
                        retry++;
                    }
                } while (retry < 5);

                if (string.IsNullOrEmpty(ipAddr)) // If we can't successfully connect
                {
                    return;
                }

                try
                {
                    IStaticPortMappingCollection portMap = new UPnPNAT().StaticPortMappingCollection;
                    if (portMap != null)
                    {
                        portMap.Add(port, "TCP", port, ipAddr, true, "xRAT 2.0 UPnP");
                    }
                }
                catch
                { }
            }).Start();
        }
示例#6
0
        public string setupPort(string ipAddress, int port, String proto)
        {
            try
            {
                UPnPNAT upnp = new UPnPNAT();
            IStaticPortMappingCollection maps = upnp.StaticPortMappingCollection;
            //foreach(IStaticPortMapping portMaps in maps)
            //{
                
            //    String IntIP = portMaps.InternalClient;
            //    int IntPort = portMaps.InternalPort;
            //    String intProto = portMaps.Protocol;
            //    if(IntPort == port)
            //    {
            //        port += 1;
            //    }
            //}

            
                maps.Add(port, proto, port, ipAddress, true, "Local Open Message Client");
                return "true";
            }
            catch (Exception ex)
            {
                return ex.ToString();
            }
            
        }
示例#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");
        }
示例#8
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="lExternalPort">外部端口</param>
        /// <param name="bstrProtocol">协议类型</param>
        /// <param name="lInternalPort">内部端口</param>
        /// <param name="bstrInternalClient">内网IP</param>
        /// <param name="bEnabled"></param>
        /// <param name="bstrDescription">名称</param>
        /// <returns></returns>
        public static bool AddUpnp(int lExternalPort, string bstrProtocol, int lInternalPort, string bstrInternalClient, bool bEnabled, string bstrDescription)
        {
            //创建COM类型
            var upnpnat  = new UPnPNAT();
            var mappings = upnpnat.StaticPortMappingCollection;

            //错误判断
            if (mappings == null)
            {
                Console.WriteLine("没有检测到路由器,或者路由器不支持UPnP功能。");
                return(false);
            }

            try
            {
                //添加之前的ipv4变量(内网IP),内部端口,和外部端口
                mappings.Add(lExternalPort, bstrProtocol, lInternalPort, bstrInternalClient, bEnabled, bstrDescription);
            }
            catch (Exception)
            {
                //  return false;
            }


            return(true);
        }
示例#9
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");
                }
            }
        }
示例#10
0
        public static void RemoveMapping(int externalPort)
        {
            UPnPNAT upnpnat = new UPnPNAT();

            if (upnpnat.StaticPortMappingCollection != null)
            {
                upnpnat.StaticPortMappingCollection.Remove(externalPort, "TCP");
            }
        }
示例#11
0
        /// <summary>
        ///     The UPnP Managed Class
        /// </summary>
        /// <remarks></remarks>
        public UPnP()
        {
            _lastInstance = this;
            //Create the new NAT Class
            _upnpnat = new UPnPNAT();

            //generate the static mappings
            GetStaticMappings();
        }
示例#12
0
        /// <summary>
        ///     The UPnP Managed Class
        /// </summary>
        /// <remarks></remarks>
        public UPnP()
        {
            _lastInstance = this;
            //Create the new NAT Class
            _upnpnat = new UPnPNAT();

            //generate the static mappings
            GetStaticMappings();
        }
示例#13
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);
        }
示例#14
0
 private static void Init()
 {
     if (UpnpNat == null)
     {
         UpnpNat = new NATUPNPLib.UPnPNAT();
     }
     if (UpnpMap == null)
     {
         UpnpMap = UpnpNat.StaticPortMappingCollection;
     }
 }
示例#15
0
文件: UPnP.cs 项目: nhz2f/xRAT
 public static void RemovePort(ushort port)
 {
     try
     {
         IStaticPortMappingCollection portMap = new UPnPNAT().StaticPortMappingCollection;
         if (portMap != null)
             portMap.Remove(port, "TCP");
     }
     catch
     { }
 }
示例#16
0
        /// <summary>Attempts to create a map to the specified port on the local machine on the next highest available external port to the one specified</summary>
        /// <returns>The actual external port mapped</returns>
        public static IPEndPoint MapPort(int localPort, int externalPortStart)
        {
            if (localPort > MaxPort)
            {
                throw new ArgumentOutOfRangeException("localPort");
            }
            if (externalPortStart > MaxPort)
            {
                throw new ArgumentOutOfRangeException("externalPortStart");
            }

            UPnPNAT upnpnat = new UPnPNAT();

            if (upnpnat.StaticPortMappingCollection != null)
            {
                DeleteTeredoMappings(upnpnat.StaticPortMappingCollection);

                int externalPort = externalPortStart;

                bool externalPortInUse;
                do
                {
                    externalPortInUse = false;
                    foreach (IStaticPortMapping mapping in upnpnat.StaticPortMappingCollection)
                    {
                        if (mapping.ExternalPort == externalPort)
                        {
                            externalPortInUse = true;
                            externalPort++;
                            break;
                        }
                    }
                } while (externalPortInUse);

                if (externalPort > MaxPort)
                {
                    throw new UPnPFailedException("All ports >= " + externalPortStart + " are in use");
                }

                IPAddress routedInterface = NetworkAdapters.GetRoutedInterface();
                if (routedInterface == null)
                {
                    throw new UPnPFailedException("Could not determine routed interface");
                }

                upnpnat.StaticPortMappingCollection.Add(externalPort, "TCP", localPort, routedInterface.ToString(), true, "MiracleSticks Server");
            }
            else
            {
                throw new UPnPFailedException("No UPnP-enabled device found");
            }

            return(GetExternalEndpoint(localPort));
        }
示例#17
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);
                                         }
                                     }
                                 }
                             }
                         }
                     }
                 }
             }
         }
     }
 }
示例#18
0
        public Task <UPnPSupportState> Prepare()
        {
            return(Task <UPnPSupportState> .Run(async() =>
            {
                try
                {
                    manager = new UPnPNAT();
                    UPnPPort testPort = new UPnPPort(1, PortType.TCP, Utils.GetLocalIP());

                    PortResult result = await CheckPort(testPort);
                    switch (result)
                    {
                    case PortResult.Opened:
                        //No more checks needed
                        State = UPnPSupportState.Supported;
                        break;

                    case PortResult.Closed:
                        //Let us check if we are able to open and close the test port.
                        PortResult r = await OpenPort(testPort);
                        if (r == PortResult.Opened)
                        {
                            r = await ClosePort(testPort);
                            if (r == PortResult.Closed)
                            {
                                State = UPnPSupportState.Supported;
                            }
                            else
                            {
                                State = UPnPSupportState.NotSupported;
                            }
                        }
                        else
                        {
                            State = UPnPSupportState.NotSupported;
                        }

                        break;

                    default:
                        //Something went wrong
                        State = UPnPSupportState.NoPrepared;
                        break;
                    }
                }
                catch (Exception)
                {
                    State = UPnPSupportState.NotSupported;
                }

                return State;
            }));
        }
示例#19
0
        public void StopServer()
        {
            Task.Run(() => {
                try
                {
                    UPnPNAT UPnP = new UPnPNAT();
                    UPnP.StaticPortMappingCollection.Remove(8088, "TCP");
                }
                catch { }

                isRunning = false;
            });
        }
示例#20
0
文件: Form1.cs 项目: ylca/PortMapping
        private void Form1_Load(object sender, EventArgs e)
        {
            //创建COM类型
            var upnpnat  = new UPnPNAT();
            var mappings = upnpnat.StaticPortMappingCollection;

            //错误判断
            if (mappings == null)
            {
                MessageBox.Show("没有检测到路由器,或者路由器不支持UPnP功能。");
            }
            loadConfig();
        }
示例#21
0
文件: UPnP.cs 项目: zzhacked/xRAT
 public static void RemovePort(ushort port)
 {
     try
     {
         IStaticPortMappingCollection portMap = new UPnPNAT().StaticPortMappingCollection;
         if (portMap != null)
         {
             portMap.Remove(port, "TCP");
         }
     }
     catch
     { }
 }
示例#22
0
文件: UPnP.cs 项目: werkamsus/xRAT
 public static void RemovePort()
 {
     try
     {
         IStaticPortMappingCollection portMap = new UPnPNAT().StaticPortMappingCollection;
         if (portMap != null)
         {
             portMap.Remove(Port, "TCP");
         }
         IsPortForwarded = false;
     }
     catch
     {
     }
 }
示例#23
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);
        }
示例#24
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);
        }
示例#25
0
        public bool InitAndFindRouter()
        {
            try
            {
                upnpnat = new UPnPNAT();
                mappings = upnpnat.StaticPortMappingCollection;

                if (mappings != null)
                    return true;
                else
                    return false;
            }
            catch
            {
                return false;
            }
        }
示例#26
0
        public _UPnPNat()
        {
            try
            {
                UPnPNAT nat = new UPnPNAT();
                if (nat.NATEventManager != null && nat.StaticPortMappingCollection != null)
                {
                    upnp = nat;
                }
            }
            catch { }

            if (upnp == null) // No configurable UPNP NAT is available.
            {
                throw new NotSupportedException();
            }
        }
示例#27
0
        public IEnumerable <MappingInfo> Get()
        {
            UPnPnat = new UPnPNAT();

            var portMappings = new List <MappingInfo>();

            var count      = Mappings.Count;
            var enumerator = Mappings.GetEnumerator();

            enumerator.Reset();
            for (int i = 0; i < count; i++)
            {
                IStaticPortMapping mapping = null;
                try
                {
                    if (enumerator.MoveNext())
                    {
                        mapping = (IStaticPortMapping)enumerator.Current;
                    }
                }
                catch
                {
                    //ignore
                }

                if (mapping != null)
                {
                    var info = new MappingInfo
                    {
                        Description       = mapping.Description,
                        ExternalIPAddress = mapping.ExternalIPAddress,
                        ExternalPort      = mapping.ExternalPort,
                        InternalClient    = mapping.InternalClient,
                        InternalPort      = mapping.InternalPort,
                        Protocol          = mapping.Protocol,
                    };
                    portMappings.Add(info);
                }
            }

            var portMappingInfos = new MappingInfo[portMappings.Count];

            portMappings.CopyTo(portMappingInfos);
            return(portMappingInfos);
        }
示例#28
0
        static void Main()
        {
            var upnpnat  = new UPnPNAT();
            var mappings = upnpnat.StaticPortMappingCollection;

            Console.WriteLine(GetLocIp());

            if (mappings != null)
            {
                Console.WriteLine("没有检测到路由器,或者路由器不支持 UPnP 功能。");
            }
            else
            {
                //mappings.Add(1080, "TCP", 10800, GetLocIp(), true, "mUPnPTest");

                Console.ReadKey();
            }
        }
示例#29
0
        static void Main(string[] args)
        {
            UPnPNAT upnpNAT = null;

            try
            {
                upnpNAT = new UPnPNAT();
            }
            catch (Exception exception)
            {
                FailureExit(HRESULT.E_ACCESSDENIED, "Could not open NATUPNP library. Exception: " + exception.Message);
            }

            if (upnpNAT == null)
            {
                FailureExit(HRESULT.E_ACCESSDENIED, "Failed to create NATUPNP library.");
            }

            PrintHeader();

            if (args.Length < 1)
            {
                PrintUsage("No command given.");
                return;
            }

            if (args[0] == "list")
            {
                ListMappings(upnpNAT, args);
            }
            else if (args[0] == "add")
            {
                AddMapping(upnpNAT, args);
            }
            else if (args[0] == "remove")
            {
                RemoveMapping(upnpNAT, args);
            }
            else
            {
                PrintUsage("Invalid command given.");
            }
        }
示例#30
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();
        }
示例#31
0
        /// <summary>Returns the external endpoint mapped to the specified port on this computer.</summary>
        public static IPEndPoint GetExternalEndpoint(int localPort)
        {
            IPAddress[] localIPs = Dns.GetHostAddresses(Dns.GetHostName());

            UPnPNAT upnpnat = new UPnPNAT();

            if (upnpnat.StaticPortMappingCollection != null)
            {
                foreach (IStaticPortMapping mapping in upnpnat.StaticPortMappingCollection)
                {
                    IPAddress localMapAddress = IPAddress.Parse(mapping.InternalClient);
                    if (localIPs.Contains(localMapAddress) && mapping.InternalPort == localPort)
                    {
                        return(new IPEndPoint(IPAddress.Parse(mapping.ExternalIPAddress), mapping.ExternalPort));
                    }
                }
            }
            return(null);
        }
示例#32
0
        public bool StartBlind(string des)
        {
            var description = des;

            //创建COM类型
            upnpnat = new UPnPNAT();
            var mappings = upnpnat.StaticPortMappingCollection;

            //错误判断
            if (mappings == null)
            {
                Console.WriteLine("没有检测到路由器,或者路由器不支持UPnP功能。");
                return(false);
            }

            //添加之前的ipv4变量(内网IP),内部端口,和外部端口
            mappings.Add(eport, "TCP", iport, innerIpv4.ToString(), true, description);
            return(true);
        }
示例#33
0
        /// <summary>
        /// UpnpServer初始化
        /// </summary>
        /// <param name="veport">外部端口</param>
        /// <param name="viport">内部端口</param>
        public UpnpServer(int veport, int viport)
        {
            try
            {
                buffer = new byte[BufferSize];

                innerIpv4 = GetHostInerIP();//获取内网IP


                //UPnP绑定信息
                eport = veport;
                iport = viport;
                var description = "LINK测试";
                //创建COM类型
                upnpnat = new UPnPNAT();
                var mappings = upnpnat.StaticPortMappingCollection;

                //错误判断
                if (mappings == null)
                {
                    Console.WriteLine("没有检测到路由器,或者路由器不支持UPnP功能。");
                    return;
                }

                //添加之前的ipv4变量(内网IP),内部端口,和外部端口
                mappings.Add(eport, "TCP", iport, innerIpv4.ToString(), true, description);

                socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                //绑定内网IP和内部端口
                socket.Bind(new IPEndPoint(innerIpv4, iport));
                socket.Listen(1);

                AsyncCallback callBack = new AsyncCallback(AcceptFinalCallback);
                //成功连接
                socket.BeginAccept(callBack, socket);
            }
            catch (Exception ex)
            {
                this.ExceptionArrived(this, new NetDataArrivedEventArgs("UpnpServer:" + ex.Message));
            }
        }
示例#34
0
文件: UPnP.cs 项目: zzhacked/xRAT
        public static void ForwardPort(ushort port)
        {
            new Thread(() =>
            {
                EndPoint endPoint;
                string ipAddr = "";
                int i         = 0;

                Retry:
                try
                {
                    TcpClient c = new TcpClient();
                    c.Connect("www.google.com", 80);
                    endPoint = c.Client.LocalEndPoint;
                    c.Close();

                    if (endPoint != null)
                    {
                        ipAddr    = endPoint.ToString();
                        int index = ipAddr.IndexOf(":");
                        ipAddr    = ipAddr.Remove(index);
                    }
                }
                catch { i++; if (i < 5)
                        {
                            goto Retry;
                        }
                }

                try
                {
                    IStaticPortMappingCollection portMap = new UPnPNAT().StaticPortMappingCollection;
                    if (portMap != null)
                    {
                        portMap.Add(port, "TCP", port, ipAddr, true, "xRAT 2.0 UPnP");
                    }
                }
                catch
                { }
            }).Start();
        }
示例#35
0
        public bool InitAndFindRouter()
        {
            try
            {
                upnpnat  = new UPnPNAT();
                mappings = upnpnat.StaticPortMappingCollection;

                if (mappings != null)
                {
                    return(true);
                }
                else
                {
                    return(false);
                }
            }
            catch
            {
                return(false);
            }
        }
示例#36
0
文件: frmMain.cs 项目: TheWizBM/YAMS
        private void UpdatePortForwards()
        {
            lblPortStatus.Text = "Checking port forwards...";
            try
            {
                tblPortForwards.Rows.Clear();
                IPAddress externalIP = YAMS.Networking.GetExternalIP();
                lblExternalIP.Text = externalIP.ToString();
                
                UPnPNAT upnpnat = new UPnPNAT();
                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";
        }
 public UpnpStaticPortMappingBehavior()
 {
     this.upnp = new UPnPNAT();
 }
示例#38
0
 /// <summary>
 /// Use NATUPNPLib to try and open a port forward
 /// </summary>
 /// <param name="intPortNumber">The port to open</param>
 /// <param name="strFriendlyName">Friendly name for the service</param>
 /// <returns>Boolean indicating whether the forward worked</returns>
 public static bool OpenUPnP(int intPortNumber, string strFriendlyName, string ipAddress = "")
 {
     if (ipAddress == "") ipAddress = GetListenIP().ToString();
     try {
         UPnPNAT upnpnat = new UPnPNAT();
         upnpnat.StaticPortMappingCollection.Add(intPortNumber, "TCP", intPortNumber, ipAddress, true, "[YAMS] " + strFriendlyName);
     
         Database.AddLog("Forwarded port " + intPortNumber + " to " + ipAddress + " for " + strFriendlyName, "networking");
         return true;
     }
     catch(Exception e) {
         string strMessage = e.Message;
         if (e.Message == "Object reference not set to an instance of an object.") strMessage = "No UPnP Router Found";
         Database.AddLog("Unable foward port " + intPortNumber + " for " + strFriendlyName + ": Exception - " + e.Message, "networking", "warn");
         return false;
     }
 }
示例#39
0
 public UpnpHelper()
 {
     NatMgr = new UPnPNAT();
 }
示例#40
0
 /// <summary>
 /// Use NATUPNPLib to try and close a previously set port forward
 /// </summary>
 /// <param name="intPortNumber">The port to open</param>
 /// <returns>Boolean indicating whether the forward worked</returns>
 public static bool CloseUPnP(int intPortNumber)
 {
     try 
     {
         UPnPNAT upnpnat = new UPnPNAT();
         upnpnat.StaticPortMappingCollection.Remove(intPortNumber, "TCP");
     
         Database.AddLog("Un-forwarded port " + intPortNumber, "networking");
         return true;
     }
     catch (Exception e)
     {
         Database.AddLog("Unable to un-forward port " + intPortNumber + ": Exception - " + e.Message, "networking", "warn");
         return false;
     }
 }
示例#41
0
文件: UPnP.cs 项目: he0x/xRAT
        public static void ForwardPort(ushort port)
        {
            Port = port;

            new Thread(() =>
            {
                string ipAddr = string.Empty;
                int retry = 0;

                do
                {
                    try
                    {
                        TcpClient c = null;
                        EndPoint endPoint;
                        try
                        {
                            c = new TcpClient();
                            c.Connect("www.google.com", 80);
                            endPoint = c.Client.LocalEndPoint;
                        }
                        finally
                        {
                            // Placed in here to make sure that a failed TcpClient will never linger!
                            if (c != null)
                            {
                                c.Close();
                            }
                        }

                        if (endPoint != null)
                        {
                            ipAddr = endPoint.ToString();
                            int index = ipAddr.IndexOf(":", StringComparison.Ordinal);
                            ipAddr = ipAddr.Remove(index);

                            // We got through successfully and with an endpoint and a parsed IP address. We may exit the loop.
                            break;
                        }
                        else
                        {
                            retry++;
                        }
                    }
                    catch
                    {
                        retry++;
                    }
                } while (retry < 5);

                if (string.IsNullOrEmpty(ipAddr)) // If we can't successfully connect
                    return;

                try
                {
                    IStaticPortMappingCollection portMap = new UPnPNAT().StaticPortMappingCollection;
                    if (portMap != null)
                        portMap.Add(port, "TCP", port, ipAddr, true, "xRAT 2.0 UPnP");
                    IsPortForwarded = true;
                }
                catch
                {
                }
            }).Start();
        }
示例#42
0
 public void Dispose()
 {
     upnpnat = null;
 }
示例#43
0
文件: UPnP.cs 项目: he0x/xRAT
 public static void RemovePort()
 {
     try
     {
         IStaticPortMappingCollection portMap = new UPnPNAT().StaticPortMappingCollection;
         if (portMap != null)
             portMap.Remove(Port, "TCP");
         IsPortForwarded = false;
     }
     catch
     {
     }
 }