/// <summary> /// Initializes the discovery of new UPnP devices. /// </summary> public static void Initialize() { _mappings = new Dictionary <int, Mapping>(); try { NatUtility.DeviceFound += DeviceFound; NatUtility.DeviceLost += DeviceLost; _discoveryComplete = false; NatUtility.StartDiscovery(); } catch (Exception) { } }
public TorrentUser(MainWindow parent) { this.parent = parent; this.engineState = EngineState.Paused; if (parent.debugMode) { this.debugWindow = new DebugWindow(); } // 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(); SetupEngine(); this.engine.StatsUpdate += this.engine_StatsUpdate; }
private void Start() { var config = _config.GetNetworkConfiguration(); if (!config.EnableUPnP || !config.EnableRemoteAccess) { return; } _logger.LogInformation("Starting NAT discovery"); NatUtility.DeviceFound += OnNatUtilityDeviceFound; NatUtility.StartDiscovery(); _timer = new Timer((_) => _createdRules.Clear(), null, TimeSpan.FromMinutes(10), TimeSpan.FromMinutes(10)); _deviceDiscovery.DeviceDiscovered += OnDeviceDiscoveryDeviceDiscovered; }
public override async Task MapAsync() { NatUtility.DeviceFound += DeviceFound; try { await Task.Run(() => NatUtility.StartDiscovery(), new CancellationTokenSource(TimeSpan.FromSeconds(5)).Token ); } catch (TaskCanceledException) { } finally { NatUtility.StopDiscovery(); } }
private void Start() { if (!_config.Configuration.EnableUPnP || !_config.Configuration.EnableRemoteAccess) { return; } _logger.LogDebug("Starting NAT discovery"); NatUtility.DeviceFound += OnNatUtilityDeviceFound; NatUtility.StartDiscovery(); _timer = new Timer(ClearCreatedRules, null, TimeSpan.FromMinutes(10), TimeSpan.FromMinutes(10)); _deviceDiscovery.DeviceDiscovered += OnDeviceDiscoveryDeviceDiscovered; _lastConfigIdentifier = GetConfigIdentifier(); }
public static void TryNatDiscovery() { try { NatUtility.Logger = Log.Channels["server"].Writer; NatUtility.Verbose = Game.Settings.Server.VerboseNatDiscovery; NatUtility.DeviceFound += DeviceFound; Game.Settings.Server.NatDeviceAvailable = false; NatUtility.StartDiscovery(); Log.Write("server", "NAT discovery started."); } catch (Exception e) { Log.Write("server", "Can't discover UPnP-enabled device: {0}", e); Game.Settings.Server.NatDeviceAvailable = false; Game.Settings.Server.AllowPortForward = false; } }
public NatTest() { // Raised whenever a device is discovered. NatUtility.DeviceFound += DeviceFound; // If you know the gateway address, you can directly search for a device at that IP //NatUtility.Search (System.Net.IPAddress.Parse ("192.168.0.1"), NatProtocol.Pmp); //NatUtility.Search (System.Net.IPAddress.Parse ("192.168.0.1"), NatProtocol.Upnp); NatUtility.StartDiscovery(); Console.WriteLine("Discovery started"); while (true) { Thread.Sleep(500000); NatUtility.StopDiscovery(); NatUtility.StartDiscovery(); } }
void _ssdp_MessageReceived(object sender, SsdpMessageEventArgs e) { var endpoint = e.EndPoint as IPEndPoint; if (endpoint == null || e.LocalEndPoint == null) { return; } string usn; if (!e.Headers.TryGetValue("USN", out usn)) { usn = string.Empty; } string nt; if (!e.Headers.TryGetValue("NT", out nt)) { nt = string.Empty; } // Filter device type if (usn.IndexOf("WANIPConnection:", StringComparison.OrdinalIgnoreCase) == -1 && nt.IndexOf("WANIPConnection:", StringComparison.OrdinalIgnoreCase) == -1 && usn.IndexOf("WANPPPConnection:", StringComparison.OrdinalIgnoreCase) == -1 && nt.IndexOf("WANPPPConnection:", StringComparison.OrdinalIgnoreCase) == -1) { return; } var identifier = string.IsNullOrWhiteSpace(usn) ? nt : usn; if (!_usnsHandled.Contains(identifier)) { _usnsHandled.Add(identifier); _logger.Debug("Calling Nat.Handle on " + identifier); NatUtility.Handle(e.LocalEndPoint.Address, e.Message, endpoint, NatProtocol.Upnp); } }
async Task <ResponseMessage> SendMessageAsync(RequestMessage message) { HttpWebRequest request = message.Encode(out byte [] body); // If this device has multiple active network devices, ensure the web request is sent from the network device which // received the response from the router. That way when we attempt to map a port, the IPAddress we are mapping to // is the same as the IPAddress which issues the WebRequest. Most uPnP implementations don't allow a device to // forward a port to a *different* IP address. request.ServicePoint.BindIPEndPointDelegate = delegate(ServicePoint servicePoint, IPEndPoint remoteEndPoint, int retryCount) { NatUtility.Log($"The WebRequest being sent to {remoteEndPoint} has been bound to local IP address {LocalAddress}"); return(new IPEndPoint(LocalAddress, 0)); }; if (NatUtility.Logger != null) { NatUtility.Log($"uPnP Request: {Environment.NewLine}{Encoding.UTF8.GetString (body)}"); } if (body.Length > 0) { request.ContentLength = body.Length; using (var stream = await request.GetRequestStreamAsync().ConfigureAwait(false)) await stream.WriteAsync(body, 0, body.Length).ConfigureAwait(false); } try { using (var response = await request.GetResponseAsync().ConfigureAwait(false)) return(await DecodeMessageFromResponse(response.GetResponseStream(), (int)response.ContentLength)); } catch (WebException ex) { // Even if the request "failed" i want to continue on to read out the response from the router using (var response = ex.Response as HttpWebResponse) { if (response == null) { throw new MappingException("Unexpected error sending a message to the device", ex); } else { return(await DecodeMessageFromResponse(response.GetResponseStream(), (int)response.ContentLength)); } } } }
private void DisposeNat() { _logger.Debug("Stopping NAT discovery"); try { NatUtility.DeviceFound -= NatUtility_DeviceFound; NatUtility.DeviceLost -= NatUtility_DeviceLost; NatUtility.UnhandledException -= NatUtility_UnhandledException; NatUtility.StopDiscovery(); } catch (Exception ex) { _logger.ErrorException("Error stopping NAT Discovery", ex); } finally { _isStarted = false; } }
/// <summary> /// Stops the driver by unhooking any event handlers and releasing any used resources. /// </summary> public override void StopDriver() { Logger.DebugFormat("{0} is stopping", DeviceDisplayNameInternal); if (_httpListener != null) { _httpListener.Close(); } if (_enableUpnp) { NatUtility.StopDiscovery(); } if (_uPnpRouter != null) { Logger.InfoFormat("{0} is removing UPnP forwarding for port {1}", DeviceDisplayNameInternal, _portNumber); _uPnpRouter.DeletePortMap(new Mapping(Protocol.Tcp, _portNumber, _portNumber)); } }
private void StopDiscovery(int timeoutMs = 2000) { Thread thr = new Thread(() => { try { NatUtility.StopDiscovery(); } catch { } }); thr.Name = "Stop Discovery"; thr.IsBackground = true; thr.Start(); if (!thr.Join(timeoutMs)) { thr.Abort(); throw new Exception("Unable to stop discovery in a timely manner."); } }
public NatTest() { NatUtility.DeviceFound += DeviceFound; NatUtility.DeviceLost += DeviceLost; NatUtility.Verbose = true; NatUtility.StartDiscovery(); //NatUtility.DirectMap(IPAddress.Parse("192.168.1.1"), MapperType.Upnp); Console.WriteLine("Discovery started"); while (true) { Thread.Sleep(500000); NatUtility.StopDiscovery(); NatUtility.StartDiscovery(); } }
/// <summary>Starts the server.</summary> /// <param name="_maxPlayers">The maximum players that can be connected simultaneously.</param> /// <param name="_port">The port to start the server on.</param> public static void Start(int _maxPlayers, int _port) { MaxPlayers = _maxPlayers; Port = _port; Debug.Log("Starting server..."); InitializeServerData(); tcpListener = new TcpListener(IPAddress.Any, Port); tcpListener.Start(); tcpListener.BeginAcceptTcpClient(TCPConnectCallback, null); udpListener = new UdpClient(Port); udpListener.BeginReceive(UDPReceiveCallback, null); NatUtility.DeviceFound += DeviceFound; NatUtility.StartDiscovery(); Debug.Log($"Server started on port {Port}."); }
private void Reload() { if (_config.Configuration.EnableUPnP) { _logger.Debug("Starting NAT discovery"); 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(); _isStarted = true; } }
private static async void DeviceFoundAsync(object sender, DeviceEventArgs e) { if (gatewayAddress.ToString() == e.Device.DeviceEndpoint.Address.ToString()) { NatUtility.StopDiscovery(); Mapping mapping = new Mapping(Protocol.Tcp, PORT, PORT); var mappingResult = await e.Device.CreatePortMapAsync(mapping); System.Console.WriteLine($"Server mapped to {mappingResult.PrivatePort} on router port {mappingResult.PublicPort}"); string hostName = Dns.GetHostName(); string myIp = Dns.GetHostEntry(hostName).AddressList[0].ToString(); var externalIp = await e.Device.GetExternalIPAsync(); gatewayDevice = e.Device; await Task.Run(() => { BackendManager.ServerPing(); }); } }
public Task ConfigureMachineForHosting() { TaskCompletionSource <object> taskCompletionSource = new TaskCompletionSource <object>(); void NatUtilityDeviceFound(object sender, DeviceEventArgs e) { NatUtility.StopDiscovery(); NatUtility.DeviceFound -= NatUtilityDeviceFound; Setup(e.Device); FirewallUtility.OpenPort(NetworkPort, "SharePlay"); taskCompletionSource.SetResult(null); } NatUtility.DeviceFound += NatUtilityDeviceFound; NatUtility.StartDiscovery(); return(taskCompletionSource.Task); }
protected WebRequest CreateRequest(string upnpMethod, string methodParameters, out byte[] body) { string ss = "http://" + this.device.HostEndPoint.ToString() + this.device.ControlUrl; NatUtility.Log("Initiating request to: {0}", ss); Uri location = new Uri(ss); HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(location); req.KeepAlive = false; req.Method = "POST"; req.ContentType = "text/xml; charset=\"utf-8\""; req.Headers.Add("SOAPACTION", "\"" + device.ServiceType + "#" + upnpMethod + "\""); string bodyString = "<s:Envelope " + "xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\" " + "s:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">" + "<s:Body>" + "<u:" + upnpMethod + " " + "xmlns:u=\"" + device.ServiceType + "\">" + methodParameters + "</u:" + upnpMethod + ">" + "</s:Body>" + "</s:Envelope>\r\n\r\n"; body = System.Text.Encoding.UTF8.GetBytes(bodyString); return(req); }
private void Start() { _logger.Debug("Starting NAT discovery"); 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)); _lastConfigIdentifier = GetConfigIdentifier(); _isStarted = true; }
private void Main_Load(object sender, EventArgs e) { idControls = 0; for (idControls = 0; idControls < Login.friendsName.Count; idControls++) { FillFrends(idControls, false); } for (int j = idControls; j < Login.friendsPendingsName.First().Count + idControls; j++) { FillFrends(j, true); } tbSend.Focus(); NatUtility.StartDiscovery(); NatUtility.DeviceFound += DeviceFound; panel3.BackColor = Color.FromArgb(124, 65, 153); FriendsAddPanel.BackColor = Color.FromArgb(124, 65, 153); panel6.BackColor = Color.FromArgb(124, 65, 153); InitializeReceiver(); metroPanel1.Enabled = false; FriendsAddPanel.Visible = false; FriendsAddPanel.Enabled = false; }
private void Start() { _logger.Debug("Starting NAT discovery"); NatUtility.EnabledProtocols = new List <NatProtocol> { NatProtocol.Pmp }; NatUtility.DeviceFound += NatUtility_DeviceFound; NatUtility.DeviceLost += NatUtility_DeviceLost; NatUtility.StartDiscovery(); _timer = _timerFactory.Create(ClearCreatedRules, null, TimeSpan.FromMinutes(10), TimeSpan.FromMinutes(10)); _deviceDiscovery.DeviceDiscovered += _deviceDiscovery_DeviceDiscovered; _lastConfigIdentifier = GetConfigIdentifier(); _isStarted = true; }
public static void TryStoppingNatDiscovery() { Log.Write("server", "Stopping NAT discovery."); try { NatUtility.StopDiscovery(); } catch (Exception e) { Log.Write("server", "Failed to stop NAT device discovery: {0}", e); Game.Settings.Server.NatDeviceAvailable = false; Game.Settings.Server.AllowPortForward = false; } if (NatDevice == null) { Log.Write("server", "No NAT devices with UPnP enabled found within {0} ms deadline. Disabling automatic port forwarding.".F(Game.Settings.Server.NatDiscoveryTimeout)); Game.Settings.Server.NatDeviceAvailable = false; Game.Settings.Server.AllowPortForward = false; } }
public void DeviceFound(object sender, DeviceEventArgs args) { try { INatDevice device = args.Device; logger.Info("Trovato dispositivo con UPNP abilitato."); logger.Info("Tipo: {0}", device.GetType().Name); logger.Info("IP Esterno del dispositivo: {0}", device.GetExternalIP()); Mapping mapTcp = new Mapping(Protocol.Tcp, Convert.ToInt32(tcpport), Convert.ToInt32(tcpport)); logger.Info("Creazione del PortMapping sul dispositivo UPNP: Protocollo={0}, Porta Public={1}, private={2}", mapTcp.Protocol, mapTcp.PublicPort, mapTcp.PrivatePort); device.CreatePortMap(mapTcp); Mapping mapUdp = new Mapping(Protocol.Udp, Convert.ToInt32(udpport), Convert.ToInt32(udpport)); logger.Info("Creazione del PortMapping sul dispositivo UPNP: Protocollo={0}, Porta Public={1}, private={2}", mapUdp.Protocol, mapUdp.PublicPort, mapUdp.PrivatePort); device.CreatePortMap(mapUdp); Mapping mapTcp2 = device.GetSpecificMapping(Protocol.Tcp, Convert.ToInt32(tcpport)); PortMappingOkTcp = true; logger.Info("Verifica del PortMapping Protocollo={0}, Porta={1} passata con successo", mapTcp2.Protocol, mapTcp2.PublicPort); Mapping mapUdp2 = device.GetSpecificMapping(Protocol.Udp, Convert.ToInt32(udpport)); PortMappingOkUdp = true; logger.Info("Verifica del PortMapping Protocollo={0}, Porta={1} passata con successo", mapUdp2.Protocol, mapUdp2.PublicPort); // Se il portfoward funziona interrompiamo il discovery // NOTA: rileviamo solo il primo router della lista NatUtility.StopDiscovery(); } catch (Exception ex) { logger.Fatal("Procedura UPNP Fallita."); logger.Fatal(ex.Message); logger.Fatal(ex.StackTrace); } }
public async Task StopAsync(bool removeExisting, CancellationToken token) { NatUtility.StopDiscovery(); var created = Mappings.Created; Mappings = Mappings.WithAllPending(); try { if (removeExisting) { foreach (var mapping in created) { foreach (var device in Devices) { token.ThrowIfCancellationRequested(); await DeletePortMapping(device, mapping); } } } } finally { RaiseMappingsChangedAsync(); } }
public void Dispose() { timer.Stop(); NatUtility.StopDiscovery(); NatUtility.DeviceFound -= NatUtility_DeviceFound; NatUtility.DeviceLost -= NatUtility_DeviceLost; lock (ports) { lock (devices) { foreach (var port in ports) { foreach (var device in devices) { Mapping mapping_tcp = new Mapping(Protocol.Tcp, port, port, 7200); Mapping mapping_udp = new Mapping(Protocol.Udp, port, port, 7200); device.BeginDeletePortMap(mapping_tcp, OnPortMapDeleted, device); device.BeginDeletePortMap(mapping_udp, OnPortMapDeleted, device); } } devices.Clear(); } ports.Clear(); } }
public UPnPPortMapper() { devices = new List <INatDevice>(); NatUtility.DeviceFound += NatUtility_DeviceFound; NatUtility.DeviceLost += NatUtility_DeviceLost; DiscoveryThread = new Thread(() => { while (true) { try { NatUtility.StartDiscovery(); Thread.Sleep(5 * 60 * 1000); //co 5 minut NatUtility.StopDiscovery(); } catch (ThreadAbortException) { } } }); DiscoveryThread.IsBackground = true; DiscoveryThread.Start(); }
public ListenPortController() { settings = SettingsManager.EngineSettings; devices = new List <INatDevice> (); tcpMapping = new Mapping(Protocol.Tcp, settings.ListenPort, settings.ListenPort); tcpMapping.Description = Defines.ApplicationName; udpMapping = new Mapping(Protocol.Udp, settings.ListenPort, settings.ListenPort); udpMapping.Description = Defines.ApplicationName; IPAddress[] addresses = null; try { addresses = NatUtility.GetLocalAddresses(false); } catch (Exception) { logger.Warn("Could not resolve hostname, port forwarding may not work"); addresses = new IPAddress[] { IPAddress.Loopback }; } NatUtility.DeviceFound += OnDeviceFound; }
public NetworkingClient(bool send, string ip, int port = 25570) { Send = send; IP = ip; Port = port; NatMapping = new NatMapping(new Mapping(Protocol.Udp, Port, Port)); if (!send) { if (NatMapping.NatDevice != null) { NatMapping.NatDevice.CreatePortMap(NatMapping.UdpMapping); IP = NatMapping.NatDevice.LocalAddress.ToString(); OnStartedUPnPMapping?.Invoke(); } if (!System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable()) { Logger.Log("No Network Connection Detected!", LoggingTarget.Network, LogLevel.Error); } else { NatUtility.DeviceFound += deviceFound; NatUtility.DeviceLost += deviceLost; NatUtility.StartDiscovery(); } UdpClient = new UdpClient(Port); EndPoint = new IPEndPoint(IPAddress.Any, Port); } else { UdpClient = new UdpClient(IP, Port); } }
void OnApplicationQuit() { if (IsServer) { CloseServer(); } if (IsClient) { Network.Disconnect(); } if (IsRegistered) { MasterServer.UnregisterHost(); } if (natDevice != null) { try { if (udpMapping != null) { natDevice.DeletePortMap(udpMapping); } if (tcpMapping != null) { natDevice.DeletePortMap(tcpMapping); } tcpMapping = udpMapping = null; Debug.Log("Deleted port mapping"); } catch (Exception ex) { Debug.Log("Failed to delete port mapping"); } } NatUtility.StopDiscovery(); }
async Task <ResponseMessage> DecodeMessageFromResponse(Stream s, int length) { StringBuilder data = new StringBuilder(); int bytesRead; byte [] buffer = new byte [10240]; // Read out the content of the message, hopefully picking everything up in the case where we have no contentlength if (length != -1) { while (length > 0) { bytesRead = await s.ReadAsync(buffer, 0, Math.Min(buffer.Length, length)).ConfigureAwait(false); data.Append(Encoding.UTF8.GetString(buffer, 0, bytesRead)); length -= bytesRead; } } else { while ((bytesRead = await s.ReadAsync(buffer, 0, buffer.Length).ConfigureAwait(false)) != 0) { data.Append(Encoding.UTF8.GetString(buffer, 0, bytesRead)); } } // Once we have our content, we need to see what kind of message it is. If we received // an error message we will immediately throw a MappingException. var dataString = data.ToString(); if (NatUtility.Logger != null) { NatUtility.Log($"uPnP Response: {Environment.NewLine}{dataString}"); } return(ResponseMessage.Decode(this, dataString)); }