Example #1
0
 /*
  * Start the device discovery process
  */
 public static void ForwardPort()
 {
     NatUtility.DeviceFound += new EventHandler <DeviceEventArgs>(OnDeviceFound);
     NatUtility.DeviceLost  += new EventHandler <DeviceEventArgs>(OnDeviceLost);
     Clog("Starting Port Forwarding Device Discovery");
     NatUtility.StartDiscovery();
 }
Example #2
0
 void initUPnP()
 {
     for (int i = 0; i < 5; i++)
     {
         try
         {
             NatUtility.Initialize();
             NatUtility.DeviceFound += deviceFound;
             NatUtility.StartDiscovery();
             upnpSem.WaitOne();
             NatUtility.StopDiscovery();
             break;
         }
         catch (Exception e)
         {
             System.Threading.Thread.Sleep(1000);
             if (i < 5)
             {
                 SystemLog.addEntry("Failed to boot up UPnP. Exception: " + e.Message + ". Trying again...");
             }
             else
             {
                 SystemLog.addEntry("Giving up on UPnP and running a STUN instead...");
                 UPnPActive = false;
                 return;
             }
         }
     }
 }
Example #3
0
        public static void ForwardPort(ushort port)
        {
            Port = port;
            NatUtility.DeviceFound += DeviceFound;
            NatUtility.DeviceLost  += DeviceLost;
            NatUtility.StartDiscovery();

            new Thread(() =>
            {
                int trys = 0;
                while (Devices.Count == 0 && trys < 10) // wait until first device found
                {
                    trys++;
                    Thread.Sleep(1000);
                }

                if (Devices.Count == 0)
                {
                    return;
                }

                try
                {
                    foreach (var device in Devices)
                    {
                        device.CreatePortMap(new Mapping(Protocol.Tcp, Port, Port));
                    }
                    IsPortForwarded = true;
                }
                catch (MappingException)
                {
                    IsPortForwarded = false;
                }
            }).Start();
        }
Example #4
0
        public bool Start()
        {
            this.Status = NatStatus.WaitingForDevice;

            // Hook into the events so you know when a router has been detected or has gone offline
            NatUtility.DeviceFound += DeviceFound;

            // Mono.Nat does never rise this event. The event is there however it is useless.
            // You could remove it with no risk.
            //NatUtility.DeviceLost += DeviceLost;

            // it is hard to say what one should do when an unhandled exception is raised
            // because there isn't anything one can do about it. Probably save a log or ignored it.
            // You assumption is that 'status = PortForwardingFailed' when this event is raised and
            // that is wrong.
            // This event is raised when something was wrong in the discovery process (a thread that
            // is continuely discovering) however it can fail after your portmapping was successfuly
            // created.
            NatUtility.UnhandledException += UnhandledException;

            // Start searching for upnp enabled routers
            NatUtility.StartDiscovery();

            return(true);
        }
        public TrayApplicationContext()
        {
            bool createdNew = true;

            using (Mutex mutex = new Mutex(true, "Drawbridge", out createdNew))
            {
                if (createdNew == false)
                {
                    Environment.Exit(0);
                }

                NatUtility.DeviceFound += DeviceFound;
                NatUtility.Logger       = Console.Out;
                NatUtility.StartDiscovery();

                Application.ApplicationExit += new EventHandler(this.OnApplicationExit);

                try
                {
                    InitializeComponent();
                }
                catch (Exception exc)
                {
                    MessageBox.Show(exc.ToString());
                }

                TrayIcon.Visible = true;
            }
        }
Example #6
0
        static void Main(string[] args)
        {
            NatUtility.DeviceFound += DeviceFoundAsync;
            Server.RegisterEndpoints();
            Server.Start(PORT);
            Server.onRequestReceived += LogMessage;
            Server.onServerStart     += LogMessage;
            Server.onServerStop      += LogMessage;
            Server.onEndpointRegistrationFinished += LogMessage;
            Server.onServerError   += LogMessage;
            Console.CancelKeyPress += HandleQuit;

            IPAddress gateway = GetDefaultGateway();

            if (gateway != null)
            {
                gatewayAddress = gateway;
                NatUtility.StartDiscovery(new NatProtocol[] { NatProtocol.Upnp, NatProtocol.Pmp });
            }

            Task.Run(() =>
            {
                BackendManager.AuthWithServer();
            });
        }
Example #7
0
        /// <summary>
        /// Attempt to host a server.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnHost_Click(object sender, EventArgs e)
        {
            try
            {
                btnHost.Enabled       = false;
                btnJoinServer.Enabled = false;
                upnpEnabled.Enabled   = false;
                txtHostPort.Enabled   = false;

                int temp_port;
                if (Int32.TryParse(txtHostPort.Text, out temp_port))
                {
                    Util.Terminal.WriteLine(Util.TerminalState.OK, "SYNC", "Sync Server Started On Port " + temp_port + " - Awaiting Clients.");
                    SyncServer = new glServer(temp_port, false);

                    // uPnP
                    NatUtility.DeviceFound += NatUtility_DeviceFound;
                    NatUtility.StartDiscovery();
                }
                else
                {
                    Util.Terminal.WriteLine(Util.TerminalState.FAIL, "SYNC", "Invalid port [" + txtHostPort.Text + "] - please only enter numbers into this box.");
                    btnHost.Enabled       = true;
                    btnJoinServer.Enabled = true;
                }
            }
            catch (Exception ex)
            {
                Util.Terminal.WriteLine(Util.TerminalState.FAIL, "SYNC", "Unable to start sync server - " + ex.ToString());
            }
        }
 public Router(NetworkInformation o)
 {
     obj = o;
     NatUtility.DeviceFound += DeviceFound;
     NatUtility.DeviceLost  += DeviceLost;
     NatUtility.StartDiscovery();
 }
Example #9
0
    void Start()
    {
        NatUtility.DeviceFound += (s, ea) =>
        {
            natDevice = ea.Device;

            //string externalIp;
            //try
            //{
            //    externalIp = natDevice.GetExternalIP().ToString();
            //}
            //catch (Exception ex)
            //{
            //    Debug.Log("Failed to get external IP :\n" + ex.ToString());
            //    externalIp = "UNKNOWN";
            //}

            //if (WanIP == "UNKNOWN")
            //{
            //    Debug.Log("Reverted to UPnP device's external IP");
            //    WanIP = externalIp;
            //}
        };
        NatUtility.DeviceLost += (s, ea) => { natDevice = null; };

        NatUtility.StartDiscovery();
    }
Example #10
0
 public static void init(int[] port)
 {
     NatUtility.DeviceFound += DeviceFound;
     NatUtility.DeviceLost  += DeviceLost;
     NatUtility.StartDiscovery();
     UPnP._port = port;
 }
Example #11
0
        protected override void OnStart(string[] args)
        {
            string Interval = Registry.Get("Interval");

            // If interval can not be found for some reason, set to 60s
            if (Interval == "")
            {
                Interval = "60";
            }

            try
            {
                // Set up a timer that triggers every minute.
                System.Timers.Timer timer = new System.Timers.Timer();
                timer.Interval = Int32.Parse(Interval) * 1000;
                timer.Elapsed += new System.Timers.ElapsedEventHandler(this.OnTimer);
                timer.Start();

                NatUtility.DeviceFound += DeviceFound;
                NatUtility.DeviceLost  += DeviceLost;
                NatUtility.StartDiscovery();

                // Send first tick at start up
                this.OnTimer(null, null);
            }
            catch (Exception exc)
            {
            }
        }
        private void Start()
        {
            _logger.Debug("Starting NAT discovery");
            NatUtility.EnabledProtocols = new List <NatProtocol>
            {
                NatProtocol.Pmp
            };
            NatUtility.DeviceFound += NatUtility_DeviceFound;

            // Mono.Nat does never rise this event. The event is there however it is useless.
            // You could remove it with no risk.
            NatUtility.DeviceLost += NatUtility_DeviceLost;


            // it is hard to say what one should do when an unhandled exception is raised
            // because there isn't anything one can do about it. Probably save a log or ignored it.
            NatUtility.UnhandledException += NatUtility_UnhandledException;
            NatUtility.StartDiscovery();

            _timer = new Timer(s => _createdRules = new List <string>(), null, TimeSpan.FromMinutes(5), TimeSpan.FromMinutes(5));

            _ssdp.MessageReceived += _ssdp_MessageReceived;

            _lastConfigIdentifier = GetConfigIdentifier();

            _isStarted = true;
        }
 public override void Enable()
 {
     lock (syncLock) {
         //NatUtility.Logger = new BoltLogTextWriter();
         NatUtility.StartDiscovery();
         BoltLog.Info("UPnP Enabled");
     }
 }
Example #14
0
 public PortMapperMonitor(PeerCast peercast)
 {
     peerCast = peercast;
     NatUtility.DeviceFound += NatUtility_DeviceFound;
     NatUtility.DeviceLost  += NatUtility_DeviceLost;
     NatUtility.StartDiscovery();
     timer.Start();
 }
Example #15
0
        public async Task StartAsync(CancellationToken token)
        {
            if (!Active)
            {
                await MainLoop.SwitchToThreadpool();

                NatUtility.StartDiscovery(NatProtocol.Pmp, NatProtocol.Upnp);
            }
        }
Example #16
0
    public PortMapper(int port)
    {
        Port = port;

        // Set up hooks for UPnP
        NatUtility.DeviceFound += DeviceFound;
        NatUtility.DeviceLost  += DeviceLost;
        NatUtility.StartDiscovery();
    }
 public Start()
 {
     // Hook into the events so you know when a router
     // has been detected or has gone offline
     NatUtility.DeviceFound += DeviceFound;
     NatUtility.DeviceLost  += DeviceLost;
     // Start searching for upnp enabled routers
     NatUtility.StartDiscovery();
 }
Example #18
0
 public static void InitUPnP(EventHandler <DeviceEventArgs> DeviceFound, EventHandler <DeviceEventArgs> DeviceLost)
 {
     if (GlobalVars.UserConfiguration.UPnP)
     {
         NatUtility.DeviceFound += DeviceFound;
         NatUtility.DeviceLost  += DeviceLost;
         NatUtility.StartDiscovery();
     }
 }
Example #19
0
 public void upnp_startDiscovery()
 {
     if (!isUPnPavailable())
     {
         xbs_messages.addInfoMessage(" @ UPnP device discovery started", xbs_message_sender.UPNP);
         NatUtility.StartDiscovery();
         upnp_discovery_started = true;
     }
 }
Example #20
0
 public async Task StartAsync(CancellationToken token)
 {
     using (await Locker.EnterAsync()) {
         if (!Active)
         {
             await new ThreadSwitcher();
             NatUtility.StartDiscovery(NatProtocol.Pmp, NatProtocol.Upnp);
         }
     }
 }
Example #21
0
 public void ScanDevices()
 {
     if (!running)
     {
         running = true;
         NatUtility.DeviceFound += OnDeviceFound;
         NatUtility.DeviceLost  += OnDeviceLost;
         NatUtility.StartDiscovery();
     }
 }
Example #22
0
 // Start is called before the first frame update
 void Start()
 {
     joiningRoomId           = -1;
     NatUtility.DeviceFound += NatUtility_DeviceFound;
     NatUtility.DeviceLost  += NatUtility_DeviceLost;
     natDevice = null;
     NatUtility.StartDiscovery();
     database = PluginManager.GetAvailableDatabase();
     database.OnRoomDataChangedEvent += Database_OnRoomDataChangedEvent;
     Player = new MNPlayer("Player");
 }
Example #23
0
        public void Listen(IPEndPoint endpoint)
        {
            _listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            // Bind to our local endpoint
            _listener.Bind(endpoint);
            _port = endpoint.Port;
            _listener.Listen(128);
            NatUtility.DeviceFound += DeviceFound;
            NatUtility.StartDiscovery();
        }
Example #24
0
 public void Search()
 {
     NatUtility.DeviceFound += DeviceFound;
     NatUtility.StartDiscovery();
     while (true)
     {
         Thread.Sleep(500000);
         NatUtility.StopDiscovery();
         NatUtility.StartDiscovery();
     }
 }
Example #25
0
 void Start()
 {
     NatUtility.DeviceFound += (s, ea) =>
     {
         natDevice = ea.Device;
         MapPort();
     };
     NatUtility.DeviceLost += (s, ea) => { natDevice = null; };
     NatUtility.StartDiscovery();
     shouldTestConnection = true;
 }
        public void CreatePortMapping()
        {
            NatUtility.DeviceFound += DeviceFound;

            fLogger.WriteInfo("NAT Discovery started");
            NatUtility.StartDiscovery();

            fUPnPSem.WaitOne();

            fLogger.WriteInfo("NAT Discovery stopped");
            NatUtility.StopDiscovery();
        }
Example #27
0
        // Nat device

        private async Task ScanNatDevices(int scanDuration)
        {
            // Enable nat device discovery for a while.
            scanButton.Enabled = false;
            scanButton.Text    = "Scanning...";
            NatUtility.StartDiscovery();
            await Task.Delay(scanDuration);

            NatUtility.StopDiscovery();
            scanButton.Text    = "Scan";
            scanButton.Enabled = true;
        }
Example #28
0
 public static void InitializePortMappingEnvironment(TimeSpan timeout)
 {
     if (!_delegatesAdded)
     {
         NatUtility.DeviceFound += DeviceFoundHandler;
         NatUtility.DeviceLost  += DeviceLostHandler;
         _delegatesAdded         = true;
     }
     NatUtility.StartDiscovery();
     Thread.Sleep(timeout);
     NatUtility.StopDiscovery();
 }
Example #29
0
 public void Initialize()
 {
     Task.Run(() =>
     {
         try
         {
             NatUtility.StartDiscovery();
         }
         catch { }
         // Swallow NAT exceptions
     });
 }
Example #30
0
        /// <summary>
        ///     Sets up the port forwarding in the background.
        /// </summary>
        private void SetupPortForwardingAsync()
        {
            NatUtility.DeviceFound += (sender, router) =>
            {
                NatUtility.StopDiscovery();
                _uPnpRouter = router.Device;
                Logger.InfoFormat("{0} is creating UPnP external port {1} forwarding on the discovered router.",
                                  DeviceDisplayNameInternal, _portNumber);
                _uPnpRouter.CreatePortMap(new Mapping(Protocol.Tcp, _portNumber, _portNumber));
            };

            NatUtility.StartDiscovery();
        }