GithubHelp home page GithubHelp logo

lontivero / open.nat Goto Github PK

View Code? Open in Web Editor NEW

This project forked from alanmcgovern/mono.nat

417.0 27.0 97.0 4.79 MB

Lightweight and easy-to-use class library to allow port forwarding in NAT devices with UPNP and/or PMP

License: MIT License

C# 99.83% Batchfile 0.17%

open.nat's Introduction

Logo

Open.NAT

Open.NAT is a lightweight and easy-to-use class library to allow port forwarding in NAT devices that support UPNP (Universal Plug & Play) and/or PMP (Port Mapping Protocol).

Goals

NATed computers cannot be reached from outside and this is particularly painful for peer-to-peer or friend-to-friend software. The main goal is to simplify communication amoung computers behind NAT devices that support UPNP and/or PMP providing a clean and easy interface to get the external IP address and map ports and helping you to achieve peer-to-peer communication.

  • Tested with .NET YES
  • Tested with Mono YES

How to use?

With nuget :

Install-Package Open.NAT

Go on the nuget website for more information.

Example

The simplest scenario:

var discoverer = new NatDiscoverer();
var device = await discoverer.DiscoverDeviceAsync();
var ip = await device.GetExternalIPAsync();
Console.WriteLine("The external IP Address is: {0} ", ip);

The following piece of code shows a common scenario: It starts the discovery process for a NAT-UPNP device and onces discovered it creates a port mapping. If no device is found before ten seconds, it fails with NatDeviceNotFoundException.

var discoverer = new NatDiscoverer();
var cts = new CancellationTokenSource(10000);
var device = await discoverer.DiscoverDeviceAsync(PortMapper.Upnp, cts);

await device.CreatePortMapAsync(new Mapping(Protocol.Tcp, 1600, 1700, "The mapping name"));

For more info please check the Wiki

Awesome software using Open.NAT

Documentation

Development

Open.NAT is been developed by Lucas Ontivero (@lontivero). You are welcome to contribute code. You can send code both as a patch or a GitHub pull request.

Here you can see what are the next features to implement. Take it a look! Build Status

Build status

NuGet version

open.nat's People

Contributors

alanmcgovern avatar bartwe avatar cdecpgl avatar jamesyfc avatar jordansolutions avatar lontivero avatar mailaender avatar renatochitolina avatar strich avatar twist84 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

open.nat's Issues

Server failed with error: 401 - Invalid Action

Detection seems to work fine:

Open.NAT Information: 0 : Start Discovery
Thread started: <Thread Pool> #3
Thread started: <Thread Pool> #4
Open.NAT Information: 0 : Searching for: UpnpSearcher
Open.NAT Verbose: 0 : UPnP Response: HTTP/1.1 200 OK
LOCATION: http://192.168.178.1:49000/igddesc.xml
SERVER: FRITZ!Box 7490 UPnP/1.0 AVM FRITZ!Box 7490 113.06.24
CACHE-CONTROL: max-age=1800
EXT:
ST: urn:schemas-upnp-org:service:WANIPConnection:1
USN: uuid:75802409-bccb-40e7-8e6a-3481C4B451E8::urn:schemas-upnp-org:service:WANIPConnection:1

Open.NAT Information: 0 : UPnP Response: Router advertised a 'urn:schemas-upnp-org:service:WANIPConnection:1' service!!!
Open.NAT Information: 0 : Found device at: http://192.168.178.1:49000/igddesc.xml
Open.NAT Information: 0 : 192.168.178.1:49000: Fetching service list
Open.NAT Information: 0 : Found device at: http://192.168.178.1:49000/igddesc.xml

Open.NAT Information: 0 : 192.168.178.1:49000: Parsed services list
Open.NAT Information: 0 : 192.168.178.1:49000: Found service: urn:schemas-upnp-org:service:WANIPConnection:1
Open.NAT Information: 0 : 192.168.178.1:49000: Found upnp service at: /igdupnp/control/WANIPConn1
Open.NAT Information: 0 : 192.168.178.1:49000: Handshake Complete
Open.NAT Information: 0 : 192.168.178.1:49000: Absolute URI detected. Host address is now: 192.168.178.1:49000
Open.NAT Information: 0 : 192.168.178.1:49000: New control url: p/control/WANIPConn1
Open.NAT Information: 0 : Stop Discovery

But every actions fails with 401 for no reason like getting the external IP address:

Open.NAT Verbose: 0 : SOAPACTION: **GetExternalIPAddress** url:http://192.168.178.1:49000/p/control/WANIPConn1
Open.NAT Verbose: 0 : <s:Envelope 
   xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" 
   s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
   <s:Body>
      <u:GetExternalIPAddress xmlns:u="urn:schemas-upnp-org:service:WANIPConnection:1">
      </u:GetExternalIPAddress>
   </s:Body>
</s:Envelope>


Open.NAT Verbose: 0 : WebException status: ProtocolError
Open.NAT Warning: 0 : Server failed with error: 401 - Invalid Action

or mapping ports:

Open.NAT Verbose: 0 : SOAPACTION: **AddPortMapping** url:http://192.168.178.1:49000/p/control/WANIPConn1
Open.NAT Verbose: 0 : <s:Envelope 
   xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" 
   s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
   <s:Body>
      <u:AddPortMapping xmlns:u="urn:schemas-upnp-org:service:WANIPConnection:1">
         <NewRemoteHost></NewRemoteHost>
         <NewExternalPort>1234</NewExternalPort>
         <NewProtocol>TCP</NewProtocol>
         <NewInternalPort>1235</NewInternalPort>
         <NewInternalClient>192.168.178.29</NewInternalClient>
         <NewEnabled>1</NewEnabled>
         <NewPortMappingDescription>OpenRA</NewPortMappingDescription>
         <NewLeaseDuration>600</NewLeaseDuration>
      </u:AddPortMapping>
   </s:Body>
</s:Envelope>

Open.NAT Verbose: 0 : WebException status: ProtocolError
Open.NAT Warning: 0 : Server failed with error: 401 - Invalid Action

Find Device's Local Ip Address

Hi, is it possible to determine the device's local IP? (not ext)
I want to compare the default gateway to device's IP address to see if it is the active connection for internet.

No valid control service was found in the service descriptor document

OpenNat - Information > Initializing
OpenNat - Information > StartDiscovery
OpenNat - Information > Searching
OpenNat - Information > Searching for: UpnpSearcher
OpenNat - Verbose > UPnP Response: HTTP/1.1 200 OK
CACHE-CONTROL: max-age=1800
EXT:
LOCATION: http://192.168.0.66:8080/upnpdev/devc/uuid_3d59d5e0-1dd2-11b2-bfd6-000391c3f0fe/00
SERVER: Q77XTLN/v4.8.1-tln-11-g4207628 UPnP/1.0 BH-upnpdev/2.0
ST: urn:schemas-upnp-org:service:WANPPPConnection:1
USN: uuid:3d59d5e0-1dd2-11b2-bfd6-000391c3f0fe::urn:schemas-upnp-org:service:ContentDirectory:2

OpenNat - Information > UPnP Response: Router advertised a 'urn:schemas-upnp-org:service:WANPPPConnection:1' service!!!
OpenNat - Information > Found device at: http://192.168.0.66:8080/upnpdev/devc/uuid_3d59d5e0-1dd2-11b2-bfd6-000391c3f0fe/00
OpenNat - Information > 192.168.0.66:8080: Fetching service list
OpenNat - Information > Found device at: http://192.168.0.66:8080/upnpdev/devc/uuid_3d59d5e0-1dd2-11b2-bfd6-000391c3f0fe/00
OpenNat - Information > 192.168.0.66:8080: Parsed services list
OpenNat - Error > Unhandled exception when trying to decode a device's response.
OpenNat - Error > Report the issue in https://github.com/lontivero/Open.Nat/issues
OpenNat - Error > Also copy and paste the following info:
OpenNat - Error > -- beging ---------------------------------
OpenNat - Error > No valid control service was found in the service descriptor document
OpenNat - Error > Data string:
OpenNat - Error > HTTP/1.1 200 OK
CACHE-CONTROL: max-age=1800
EXT:
LOCATION: http://192.168.0.66:8080/upnpdev/devc/uuid_3d59d5e0-1dd2-11b2-bfd6-000391c3f0fe/00
SERVER: Q77XTLN/v4.8.1-tln-11-g4207628 UPnP/1.0 BH-upnpdev/2.0
ST: urn:schemas-upnp-org:service:WANPPPConnection:1
USN: uuid:3d59d5e0-1dd2-11b2-bfd6-000391c3f0fe::urn:schemas-upnp-org:service:ContentDirectory:2

OpenNat - Error > -- end ------------------------------------

Open.NAT - Warning > Server failed with error: 402 - Invalid Argument

Hey there, just wanted to report what I got when I ran your test utility incase others come across the same issue:
*Open.NAT - Information > Start Discovery
Open.NAT - Information > Searching for: UpnpSearcher
Open.NAT - Information > UPnP Response: Router advertised a 'urn:schemas-upnp-org:service:WANIPConnection:1' service!!!
Open.NAT - Information > Found device at: http://192.168.1.1:1780/InternetGatewayDevice.xml
Open.NAT - Information > 192.168.1.1:1780: Fetching service list
Open.NAT - Information > Found device at: http://192.168.1.1:1780/InternetGatewayDevice.xml
Open.NAT - Information > 192.168.1.1:1780: Parsed services list
Open.NAT - Information > 192.168.1.1:1780: Found service: urn:schemas-upnp-org:service:WANIPConnection:1
Open.NAT - Information > 192.168.1.1:1780: Found upnp service at: /control?WANIPConnection
Open.NAT - Information > 192.168.1.1:1780: Handshake Complete
Open.NAT - Information > Stop Discovery
Open.NAT - Information > GetExternalIPAsync - Getting external IP address
Open.NAT - Information > CreatePortMapAsync - Creating port mapping Tcp 1703 --> 192.168.1.100:1603 (Open.Nat (Manual lifetime))
Open.NAT - Warning > Server failed with error: 402 - Invalid Argument
EXCEPTION: Error 402: Invalid Argument
*

ConflictInMappingEntry giant exception

What does this exception mean:

2016/07/20 01:01:46 UTC-07:00 [ERROR] Trying to open port 28010: System.AggregateException: One or more errors occurred. ---> Open.Nat.MappingException: Error 718: ConflictInMappingEntry
   at Open.Nat.SoapClient.GetXmlDocument(String response) in C:\Github\Open.NAT\Open.Nat\Upnp\SoapClient.cs:line 247
   at Open.Nat.SoapClient.<InvokeAsync>d__3.MoveNext() in C:\Github\Open.NAT\Open.Nat\Upnp\SoapClient.cs:line 129
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Open.Nat.StreamExtensions.<TimeoutAfter>d__7`1.MoveNext() in C:\Github\Open.NAT\Open.Nat\Utils\Extensions.cs:line 0
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Open.Nat.UpnpNatDevice.<CreatePortMapAsync>d__4.MoveNext() in C:\Github\Open.NAT\Open.Nat\Upnp\UpnpNatDevice.cs:line 185
   --- End of inner exception stack trace ---
   at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
   at System.Threading.Tasks.Task.Wait(Int32 millisecondsTimeout, CancellationToken cancellationToken)

?

Include full request/response in tracing

Oftentimes is very usefull to have the http requests and responses for understanding misbehaviours. Also, use System.Net trace listener and remove redundant traces.

Error when Service control urls have question marks

When I tested out the ConsoleTest program, I ran into problems at
device.GetExternalIPAsync() on three different routers.

Open.NAT Information: 0 : Found device at: http://10.10.204.1:1780/InternetGatewayDevice.xml
Open.NAT Information: 0 : 10.10.204.1:1780: Fetching service list
Open.NAT Information: 0 : Found device at: http://10.10.204.1:1780/InternetGatewayDevice.xml
Open.NAT Information: 0 : 10.10.204.1:1780: Parsed services list
Open.NAT Information: 0 : 10.10.204.1:1780: Found service: urn:schemas-upnp-org:service:WANIPConnection:1
Open.NAT Information: 0 : 10.10.204.1:1780: Found upnp service at: /control?WANIPConnection
Open.NAT Information: 0 : 10.10.204.1:1780: Handshake Complete
Open.NAT Information: 0 : Stop Discovery
Open.NAT Verbose: 0 : SOAPACTION: **GetExternalIPAddress** url:http://10.235.204.1:1780/control%3FWANIPConnection
Open.NAT Verbose: 0 : <s:Envelope 
   xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" 
   s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
   <s:Body>
      <u:GetExternalIPAddress xmlns:u="urn:schemas-upnp-org:service:WANIPConnection:1">
      </u:GetExternalIPAddress>
   </s:Body>
</s:Envelope>
Open.NAT Verbose: 0 : WebException status: ServerProtocolViolation

Notice that the UriBuilder replaced the question mark character to %3F. This caused the router to return 404 error.

Solution:

ServiceControlUri = new Uri(string.Format("http://{0}:{1}{2}", locationUri.Host, locationUri.Port, serviceControlUrl));

My second problem is in GetAllMappingsAsync, one of my routers (sagemcom vdsl modem/router)
returns mapping entry with internalclient empty. My fix is as follow

public override async Task<IEnumerable<Mapping>> GetAllMappingsAsync()
{
    var index = 0;
    var mappings = new List<Mapping>();
    while (true)
    {
         try
         {
             var message = new GetGenericPortMappingEntry(index);

             var responseData = await _soapClient
                  .InvokeAsync("GetGenericPortMappingEntry", message.ToXml())
                  .TimeoutAfter(TimeSpan.FromSeconds(4));

             var responseMessage = new GetPortMappingEntryResponseMessage(responseData, DeviceInfo.ServiceType, true);
             if (!string.IsNullOrEmpty(responseMessage.InternalClient))
             {
                  var mapping = new Mapping(responseMessage.Protocol
                      , IPAddress.Parse(responseMessage.InternalClient)
                      , responseMessage.InternalPort
                      , responseMessage.ExternalPort
                      , responseMessage.LeaseDuration
                      , responseMessage.PortMappingDescription);
                  mappings.Add(mapping);
              }
              index++;
        }
        catch (MappingException e)
        {
            System.Diagnostics.Debug.WriteLine(e.ToString());
            if ((e.ErrorCode == UpnpConstants.SpecifiedArrayIndexInvalid) ||
                (e.ErrorCode == UpnpConstants.NoSuchEntryInArray)) break; // there are no more mappings
                    throw;
        }
    }

   return mappings.ToArray();
}

Question: Is there a reason to use UriBuilder if it replaces what it considers illegal characters?

Evaluate the use of useUnsafeHeaderParsing for buggy devices

Forum: article "Open.NAT - A NAT Traversal library for .NET and Mono"
Subject: 3 bugs (View)
Sender: gunnarD
Date: Thursday, August 11, 2016 9:53am

Need to add this to app.config, else I get exception "The server committed a protocol violation. Section=ResponseStatusLine"

<system.net>
  <settings>
    <httpWebRequest useUnsafeHeaderParsing="true" />
  </settings>
</system.net>

Catch Exception in 3.5 .Net environment

Hi lucas thanks for your fgrat jib, you lib is really usefull for my project.

I encountering a problem to get Exception under 3.5 .NET on GUI project

private Task OpenUPNP()
        {
            var nat = new NatDiscoverer();
            var cts = new CancellationTokenSource();
            cts.CancelAfter(5000);
            Device = null;
            IPAddress ip = null;
            return nat.DiscoverDeviceAsync(PortMapper.Upnp, cts)
                .ContinueWith(task =>
                {
                    Device = task.Result;
                    return Device.GetExternalIPAsync();

                })
                .Unwrap()
                .ContinueWith(task =>
                {
                    LocalIP = task.Result;
                    return Device.CreatePortMapAsync(new Mapping(Open.Nat.Protocol.Udp, m_Port, m_Port, 0, "FFSTracker"));
                });
        }
private void InitUPNP(bool flag)
        {
            if (flag)
            {
                if (m_bUPNP) return;
                try
                {
                    OpenUPNP().Wait();
                    Log.LogMessage("P2PManager: Adresse IP = " + LocalIP.ToString(), Color.DarkBlue, 1);
                    Log.LogMessage("P2PManager: Ouverture du port UPNP ok", Color.DarkBlue, 1);
                    m_bUPNP = true;
                }
                catch (NatDeviceNotFoundException e)
                {
                    Log.LogMessage("P2PManager: Aucun routeur compatible UPNP dรฉtectรฉ.", Color.DarkViolet);
                    return;
                }
                catch (MappingException me)
                {
                    switch (me.ErrorCode)
                    {
                        case 718:
                            Log.LogMessage("P2PManager: Le port externer est dรฉjร  utilisรฉ.", Color.DarkViolet);
                            break;
                        case 728:
                            Log.LogMessage("P2PManager: La taple du routeur est pleine.");
                            break;
                    }
                }
            }
            else
            {
                if ((!m_bUPNP) || (Device==null)) return;
                Task myTask = new Task(() =>
                { 
                    try
                    {
                        Device.DeletePortMapAsync(new Mapping(Open.Nat.Protocol.Udp, m_Port, m_Port));
                        Log.LogMessage("P2PManager: Fermeture du port UPNP ok", Color.Blue, 1);
                    }
                    catch (Open.Nat.MappingException e)
                    {
                        Log.LogMessage("P2PManager: Fermeture du port UPNP impossible: " + e.Message, Color.DarkViolet, 1);
                    }
                });
                myTask.Start();
                myTask.Wait();
                m_bUPNP = false;
            }
        }

The OpenPNP tasks not trigger a catch and give me an unhandled exception crash when for exemple, My router have UPNP disable.

Unfortunatly, I Can't port my code on .NET 4 or more, because I have dependency block me on 3.5

Crash when trying to delete a port map that doesn't exist

If you try to delete a port map that doesn't exist the application will generate an unhandled exception:

Error 714: NoSuchEntryInArray

and then crash.

Surrounding the delete port map method avoids the crash, however this should be handled internally.

Try to reinterprete error code 402 InvalidArguments for buggy devices

Forum: article "Open.NAT - A NAT Traversal library for .NET and Mono"
Subject: 3 bugs (View)
Sender: gunnarD
Date: Thursday, August 11, 2016 9:53am

Also many routers return error 402 InvalidArguments instead of the more specific error(s), so I had to check for UpnpConstants.InvalidArguments in GetSpecificMappingAsync, GetAllMappingsAsync and DeletePortMapAsync and handle it the same way as the specific error ( UpnpConstants.SpecifiedArrayIndexInvalid \ UpnpConstants.NoSuchEntryInArray).

Discovery Timeout never returns

I've been running the default console test on a number of machines to test how well the framework works and I've run into an issue on one of the machines where the discovery timeout never occurs. The last log it ever prints is the searching information (It finds nothing).
I haven't been able to determine a root cause there yet and since its the code out of the box I haven't much information to provide. Let me know if you need more.

Parameterless DiscoverDeviceAsync method throws Exception

From CodeProject.com

Great library. I was able to access a nodejs site on my pc from my phone using the external ip address and port. One observation though

This throws an exception

var device = await discoverer.DiscoverDeviceAsync();

but this works fine

var device = await discoverer.DiscoverDeviceAsync(PortMapper.Upnp, cts);

Not sure why but details of the exception are below. The small sample I wrote works great.

Exception (from vs)

System.ArgumentOutOfRangeException was unhandled by user code
  HResult=-2146233086
  Message=Specified argument was out of the range of valid values.
Parameter name: poertMapper
  Source=Open.Nat
  ParamName=poertMapper
  StackTrace:
       at Open.Nat.Guard.IsTrue(Boolean exp, String paramName)
       at Open.Nat.NatDiscoverer.<DiscoverDeviceAsync>d__4.MoveNext()
    --- End of stack trace from previous location where exception was thrown ---
       at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
       at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
       at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
       at Open.Nat.NatDiscoverer.<DiscoverDeviceAsync>d__0.MoveNext()
    --- End of stack trace from previous location where exception was thrown ---
       at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
       at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
       at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
       at OpenNATTest.Program.<Do1>d__0.MoveNext() in c:\Users\Me\Documents\Visual Studio 2013\Projects\CPTests\OpenNATTest\Program.cs:line 23

InnerException:

UpnpNatDevice.CreatePortMapAsync does not await retry.

UpnpNatDevice.CreatePortMapAsync (without NET35 defined) does not await the nested CreatePortMapAsync calls.

Suggested fix:

    public override async Task CreatePortMapAsync(Mapping mapping)
    {
        Guard.IsNotNull(mapping, "mapping");
        if(mapping.PrivateIP.Equals(IPAddress.None)) mapping.PrivateIP =  DeviceInfo.LocalAddress;

        NatDiscoverer.TraceSource.LogInfo("CreatePortMapAsync - Creating port mapping {0}", mapping);
        bool retry = false;
        try
        {
            var message = new CreatePortMappingRequestMessage(mapping);
            await _soapClient
                .InvokeAsync("AddPortMapping", message.ToXml())
                .TimeoutAfter(TimeSpan.FromSeconds(4));
            RegisterMapping(mapping);
        }
        catch(MappingException me)
        {
            switch (me.ErrorCode)
            {
                case UpnpConstants.OnlyPermanentLeasesSupported:
                    NatDiscoverer.TraceSource.LogWarn("Only Permanent Leases Supported - There is no warranty it will be closed");
                    mapping.Lifetime = 0;
                    // We create the mapping anyway. It must be released on shutdown.
                    mapping.LifetimeType = MappingLifetime.ForcedSession;
                    retry = true;
                    break;
                case UpnpConstants.SamePortValuesRequired:
                    NatDiscoverer.TraceSource.LogWarn("Same Port Values Required - Using internal port {0}", mapping.PrivatePort);
                    mapping.PublicPort = mapping.PrivatePort;
                    retry = true;
                    break;
                case UpnpConstants.RemoteHostOnlySupportsWildcard:
                    NatDiscoverer.TraceSource.LogWarn("Remote Host Only Supports Wildcard");
                    mapping.PublicIP = IPAddress.None;
                    retry = true;
                    break;
                case UpnpConstants.ExternalPortOnlySupportsWildcard:
                    NatDiscoverer.TraceSource.LogWarn("External Port Only Supports Wildcard");
                    throw;
                case UpnpConstants.ConflictInMappingEntry:
                    NatDiscoverer.TraceSource.LogWarn("Conflict with an already existing mapping");
                    throw;
                default:
                    throw;
            }
        }
        if (retry)
            await CreatePortMapAsync(mapping);
    }

Open.Nat.ConsoleTest: Stream does not support writing

mono --debug Open.Nat.ConsoleTest.exe
Open.NAT - Information > Start Discovery
Open.NAT - Information > Searching for: UpnpSearcher
Open.NAT - Information > Stop Discovery
Open.NAT - Information > Device not found. Common reasons:
Open.NAT - Information >    * No device is present or,
Open.NAT - Information >    * Upnp is disabled in the router or
Open.NAT - Information >    * Antivirus software is filtering SSDP (discovery protocol).
Not found
Press any key to exit...

System.NotSupportedException: Stream does not support writing
  at System.IO.FileStream.Write (System.Byte[] array, System.Int32 offset, System.Int32 count) [0x000a5] in /home/abuild/rpmbuild/BUILD/mono-4.6.0/mcs/class/corlib/System.IO/FileStream.cs:632 
  at System.IO.StreamWriter.Flush (System.Boolean flushStream, System.Boolean flushEncoder) [0x00094] in /home/abuild/rpmbuild/BUILD/mono-4.6.0/mcs/class/referencesource/mscorlib/system/io/streamwriter.cs:316 
  at System.IO.StreamWriter.Write (System.String value) [0x00086] in /home/abuild/rpmbuild/BUILD/mono-4.6.0/mcs/class/referencesource/mscorlib/system/io/streamwriter.cs:442 
  at System.IO.CStreamWriter.InternalWriteString (System.String val) [0x00000] in /home/abuild/rpmbuild/BUILD/mono-4.6.0/mcs/class/corlib/System/CStreamWriter.cs:128 
  at (wrapper remoting-invoke-with-check) System.IO.CStreamWriter:InternalWriteString (string)
  at System.TermInfoDriver.WriteConsole (System.String str) [0x00007] in /home/abuild/rpmbuild/BUILD/mono-4.6.0/mcs/class/corlib/System/TermInfoDriver.cs:146 
  at System.TermInfoDriver.ChangeColor (System.String format, System.ConsoleColor color) [0x00025] in /home/abuild/rpmbuild/BUILD/mono-4.6.0/mcs/class/corlib/System/TermInfoDriver.cs:400 
  at System.TermInfoDriver.set_ForegroundColor (System.ConsoleColor value) [0x00011] in /home/abuild/rpmbuild/BUILD/mono-4.6.0/mcs/class/corlib/System/TermInfoDriver.cs:432 
  at System.ConsoleDriver.set_ForegroundColor (System.ConsoleColor value) [0x0001f] in /home/abuild/rpmbuild/BUILD/mono-4.6.0/mcs/class/corlib/System/ConsoleDriver.cs:134 
  at System.Console.set_ForegroundColor (System.ConsoleColor value) [0x00000] in /home/abuild/rpmbuild/BUILD/mono-4.6.0/mcs/class/corlib/System/Console.cs:587 
  at Open.Nat.ConsoleTest.ColorConsoleTraceListener.WriteColor (System.String message, System.ConsoleColor color) [0x00002] in /home/matthias/Entwicklung/Mono.Nat/Open.Nat.ConsoleTest/ColorConsoleTraceListener.cs:84 
  at Open.Nat.ConsoleTest.ColorConsoleTraceListener.TraceEvent (System.Diagnostics.TraceEventCache eventCache, System.String source, System.Diagnostics.TraceEventType eventType, System.Int32 id, System.String format, System.Object[] args) [0x000f0] in /home/matthias/Entwicklung/Mono.Nat/Open.Nat.ConsoleTest/ColorConsoleTraceListener.cs:69 
  at System.Diagnostics.TraceSource.TraceEvent (System.Diagnostics.TraceEventType eventType, System.Int32 id, System.String format, System.Object[] args) [0x0005d] in /home/abuild/rpmbuild/BUILD/mono-4.6.0/mcs/class/referencesource/System/compmod/system/diagnostics/TraceSource.cs:327 
  at Open.Nat.StreamExtensions.LogInfo (System.Diagnostics.TraceSource source, System.String format, System.Object[] args) [0x00006] in /home/matthias/Entwicklung/Mono.Nat/Open.Nat/Utils/Extensions.cs:59 
  at Open.Nat.Finalizer.Finalize () [0x00001] in /home/matthias/Entwicklung/Mono.Nat/Open.Nat/Finalizer.cs:32

I don't really understand this error otherwise I would have come up with a fix.

UpnpNatDevice.GetSpecificMappingAsync returns wrong protocol

UpnpNatDevice.GetSpecificMappingAsync (without NET35 defined)

Can return mappings with a different protocol than requested.
This is likely due to router firmware bugs or it binding a portnumber and ignoring the protocol.
(Replicated with a Fritz!box 7490)

Given that the protocol is an argument to the function the result can take this value directly and log a trace noting the conflict.

Suggested code:

    public override async Task<Mapping> GetSpecificMappingAsync (Protocol protocol, int publicPort)
    {
        Guard.IsTrue(protocol == Protocol.Tcp || protocol == Protocol.Udp, "protocol");
        Guard.IsInRange(publicPort, 0, ushort.MaxValue, "port");

        NatDiscoverer.TraceSource.LogInfo("GetSpecificMappingAsync - Getting mapping for protocol: {0} port: {1}", Enum.GetName(typeof(Protocol), protocol), publicPort);

        try
        {
            var message = new GetSpecificPortMappingEntryRequestMessage(protocol, publicPort);
            var responseData = await _soapClient
                .InvokeAsync("GetSpecificPortMappingEntry", message.ToXml())
                .TimeoutAfter(TimeSpan.FromSeconds(4));

            var messageResponse = new GetPortMappingEntryResponseMessage(responseData, DeviceInfo.ServiceType, false);


            if (messageResponse.Protocol != protocol)
                NatDiscoverer.TraceSource.LogWarn("Router responded to a protocol {0} query with a protocol {1} answer, work around applied.", protocol, messageResponse.Protocol);

            return new Mapping(protocol
                , IPAddress.Parse(messageResponse.InternalClient)
                , messageResponse.InternalPort
                , publicPort // messageResponse.ExternalPort is short.MaxValue
                , messageResponse.LeaseDuration
                , messageResponse.PortMappingDescription);
        }
        catch (MappingException e)
        {
            // there are no more mappings
            if (e.ErrorCode == UpnpConstants.SpecifiedArrayIndexInvalid
             || e.ErrorCode == UpnpConstants.NoSuchEntryInArray
                // DD-WRT Linux base router (and others probably) fails with 402-InvalidArgument when index is out of range
             || e.ErrorCode == UpnpConstants.InvalidArguments
                // LINKSYS WRT1900AC AC1900 it returns errocode 501-PAL_UPNP_SOAP_E_ACTION_FAILED
             || e.ErrorCode == UpnpConstants.ActionFailed)
            {
                NatDiscoverer.TraceSource.LogWarn("Router failed with {0}-{1}. No more mappings is assumed.", e.ErrorCode, e.ErrorText);
                return null;
            }
            throw;
        }
    }

Allow creation of port mapping with arbitrary Private IP

User @at1993 requests in issue #22

I do have a proposal though. I would like to use Open.NAT in one of my application which managed the "Internet of Things". Some of these gadgets needs to be accessible from outside the router. The app will manage the port mappings when necessary. In Open.NAT, the PrivateIP is forced to DeviceInfo.LocalAddress in CreatePortMapAsync. Two things need to be modified as followed.

  1. Change one of the Mapping constructor to public.
public Mapping(Protocol protocol, IPAddress privateIP, int privatePort, int publicPort)
            : this(protocol, privateIP, privatePort, publicPort, 0, "Open.Nat")
        {
        }

2.Check PrivateIP before before setting it to DeviceInfo.LocalAddress

public override async Task CreatePortMapAsync(Mapping mapping)
{
            Guard.IsNotNull(mapping, "mapping");
            if (mapping.PrivateIP==null) mapping.PrivateIP = DeviceInfo.LocalAddress;
   ...
}

net20 support

hi, i'm a unity3d user and it only supported net20, i can't use System.Threading.Tasks.
is any idea to solve this problem?

NatDeviceNotFoundException Problem

Hello,

I want to use this library in my app. But ConsoleTest app is sometimes found NAT device, most of times isn't found. What could cause of this?

Open.NAT does not work on Linux

If you try to run Open.NAT Console Test on Linux (Ubuntu 14.04 Mono 3.2.8) it fails - It never finds a UPnP device where a Windows PC on the same network will. It is likely an issue with the way Open.NAT is using the networking framework where it is not properly listening to the right interfaces.

Additionally, even if you apply a verbose logging level Open.NAT does not appear to log verbosely.

You might need to review you code with respect to Mono 3 and ensure it works as you expect.

Open.NAT failing to open a port

                NatDiscoverer natdisc = new NatDiscoverer();
                NatDevice natdev = natdisc.DiscoverDeviceAsync().Result;
                Mapping map = natdev.GetSpecificMappingAsync(Protocol.Tcp, TheServer.Port).Result;
                if (map != null)
                {
                    natdev.DeletePortMapAsync(map).Wait();
                }
                natdev.CreatePortMapAsync(new Mapping(Protocol.Tcp, TheServer.Port, TheServer.Port, "Test")).Wait();
                map = natdev.GetSpecificMappingAsync(Protocol.Tcp, TheServer.Port).Result;
                SysConsole.Output(OutputType.INIT, "Successfully opened server to public address " + map.PrivateIP + " or " + map.PublicIP + ", with port " + map.PrivatePort + " or " + map.PublicPort + ", as " + map.Description);

This outputs: 192.168.0.9 or 255.255.255.255 with port 28010 or 65535 as Test.

The PublicIP and PublicPort appear to just be their individual maximum values.
Additionally, the port is not open. I connected to it through HTTP to test (The server is configured to respond to that) via http://<my external ip>:28010. This failed to connect, and eventually timed out. http://localhost:28010 functions. I confirmed my server and address choice function fine by temporarily configuring a manual router port forward and then reconnecting, which worked fine.

Any idea what has gone wrong here?

GetSpecificMappingAsync broken

GetSpecificMappingAsync calls GetGenericPortMappingEntryResponseMessage which passes it's type name to the base class and fails on the XML node lookup. Need to create a new class GetSpecificPortMappingEntryResponseMessage and lose the bool _genericMapping flag in the constructors.

Error encoding service control url

Forum: article "Open.NAT - A NAT Traversal library for .NET and Mono"
Subject: 3 bugs (View)
Sender: gunnarD
Date: Thursday, August 11, 2016 9:53am

Problem in UpnpNatDeviceInfo:

Had to change from this

var builder = new UriBuilder("http", locationUri.Host, locationUri.Port, serviceControlUrl);
ServiceControlUri = builder.Uri;

to this

var builder = new UriBuilder("http", locationUri.Host, locationUri.Port);
ServiceControlUri = new Uri(builder.Uri + serviceControlUrl.TrimStart('/'));

else I got HTTP error 404 Not found (problem with url, /control?WANIPConnection became /control%3FWANIPConnection

PCP support?

Hi, are you planning to implement PCP in future?

error when i test code

OpenNat Information: 0 : UPnP Response: Router advertised a 'urn:schemas-upnp-org:service:WANIPConnection:1' service!!!
OpenNat Error: 0 : Unhandled exception when trying to decode a device's response.
OpenNat Error: 0 : Report the issue in https://github.com/lontivero/Open.Nat/issues
OpenNat Error: 0 : Also copy and paste the following info:
OpenNat Error: 0 : -- beging ---------------------------------
OpenNat Error: 0 : The given key was not present in the dictionary.
OpenNat Error: 0 : Data string:
OpenNat Error: 0 : HTTP/1.1 200 OK
CACHE-CONTROL: max-age=100
DATE: Fri, 06 Jun 2014 05:24:52 GMT
EXT:
LOCATION: http://192.168.0.1:1900/igd.xml
SERVER: ipos/7.0 UPnP/1.0 TL-WR740N/4.0
ST: urn:schemas-upnp-org:service:WANIPConnection:1
USN: uuid:9f0865b3-f5da-4ad5-85b7-7404637fdf37::urn:schemas-upnp-org:service:WANIPConnection:1

Action not authorized From GetAllMappingsAsync

The GetAllMappingsAsync failed in a Sagemcom Fast 5250 router.
The error returned as below with wireshark capature attached.

Open.NAT - Information > GetAllMappingsAsync - Getting all mappings
Open.NAT - Warning > Server failed with error: 606 - Action not authorized

Any ideas?

untitled

Exception of type 'Open.Nat.NatDeviceNotFoundException' was thrown.

Here's my code:

using System;
using System.Net;
using System.Threading;
using Open;
using Open.Nat;

namespace CPortOpener
{
    class MainClass
    {
        public static void Main (string[] args)
        {
            openPort ();
            Console.ReadLine ();
        }

        public static async void openPort ()
        {
            try
            {
                var discoverer = new NatDiscoverer();
                var cts = new CancellationTokenSource(15000);
                var device = await discoverer.DiscoverDeviceAsync(PortMapper.Upnp, cts);

                await device.CreatePortMapAsync(new Mapping(Protocol.Tcp, 1600, 1700, "The mapping name"));
            }
            catch (Exception ex)
            {
                Console.WriteLine (ex.Message);
            }
        }
    }
}

I'm getting this Exception:
Exception of type 'Open.Nat.NatDeviceNotFoundException' was thrown.

Using Open.NAT

Hello Sir,

I had to signup in order to get to you, glad for that anyway.
Firstly I have a remote desktop application like teamviewer, it works on same network but going over the internet I have serious issues. I downloaded the Open.NAT and add it up to my project in vb.net as dependency. I have serious issues with these two statement in vb.net. Please guide me on this.

var device = await discoverer.DiscoverDeviceAsync();
var ip = await device.GetExternalIPAsync();

I also believe with your Open.NAT solution I should be able to achieve my goal of port forwarding a particular port.
If you have better idea or solution kindly assist me.

Thank you.

Error while obtaining my external IP address

A week ago I tried the library for the 1st time, so to see if it works OK I ran the official test that @lontivero has specified, but it failed almost right away.
The problem occurs to be a bad Http request, in the method GetExternalIPAddressResponse.
Here's a log file I've added to show the exception being thrown along with the built-in tracing: Log File

I've also tried restarting my router, assigning a static IP address, and using the NATUPnP 1.0 type library, which actually works just fine.

Using Open.Nat on Raspberian

The aplication is running on rapberry Pi with Raspberian. I had installed the mono framework and MonoDevelop to use the Open.Nat.

When I tried the Open:nat.ConsoleTest the application crash with error

System.EntryPointNotFoundException: SwitchToThread
at at (wrapper managed-to-native) System.Threading.Platform:SwitchToThread ()
at System.Threading.Platform.Yield () [0x00000] in :0
at System.Threading.ManualResetEventSlim.Wait (Int32 millisecondsTimeout, CancellationToken cancellationToken) [0x0006d] in :0
at System.Threading.Tasks.Task.InternalWait (Int32 millisecondsTimeout, CancellationToken cancellationToken) [0x00031] in :0
at System.Threading.Tasks.Task.Wait (Int32 millisecondsTimeout, CancellationToken cancellationToken) [0x0001f] in :0
at System.Threading.Tasks.Task.Wait () [0x00007] in :0
at Open.Nat.ConsoleTest.NatTest.Main (System.String[] args) [0x00006] in /home/pi/Documents/Open.Nat/Open.NAT/Open.Nat.ConsoleTest/Main.cs:40

on the network log file I have only 2 lines

Open.NAT Information: 0 : Start Discovery
Open.NAT Information: 0 : Searching for: UpnpSearcher

The UPnP is enabled on my router.

Open.NAT Warning: 0 : Server failed with error: 714 - NoSuchEntryInArray

I'm able to CreatePortMapAsync with no problem and even show the routers table via a GetExternalIPAsync call...
Open.NAT Information: 0 : Start Discovery
BEGIN!
Open.NAT Information: 0 : Searching for: UpnpSearcher
The thread 0x3734 has exited with code 0 (0x0).
Open.NAT Information: 0 : UPnP Response: Router advertised a 'urn:schemas-upnp-org:service:WANIPConnection:1' service!!!
Open.NAT Information: 0 : Found device at: http://192.168.1.1:1780/InternetGatewayDevice.xml
Open.NAT Information: 0 : 192.168.1.1:1780: Fetching service list
Open.NAT Information: 0 : Found device at: http://192.168.1.1:1780/InternetGatewayDevice.xml
Open.NAT Information: 0 : 192.168.1.1:1780: Parsed services list
Open.NAT Information: 0 : 192.168.1.1:1780: Found service: urn:schemas-upnp-org:service:WANIPConnection:1
Open.NAT Information: 0 : 192.168.1.1:1780: Found upnp service at: /control?WANIPConnection
Open.NAT Information: 0 : 192.168.1.1:1780: Handshake Complete
Open.NAT Information: 0 : Stop Discovery
Open.NAT Information: 0 : CreatePortMapAsync - Creating port mapping Tcp 1501 --> 192.168.1.100:1501 (Open.NAT) - thisHost
However when calling await device.DeletePortMapAsync(mapping); function I get
Open.NAT Information: 0 : DeletePortMapAsync - Deleteing port mapping Tcp 1501 --> 192.168.1.100:1501 (Open.NAT) - thisHost
[Removing TCP mapping] 1501
Exception thrown: 'System.Net.WebException' in mscorlib.dll
Open.NAT Warning: 0 : Server failed with error: 714 - NoSuchEntryInArray
Exception thrown: 'Open.Nat.MappingException' in Open.Nat.dll
Exception thrown: 'Open.Nat.MappingException' in mscorlib.dll
Exception thrown: 'Open.Nat.MappingException' in mscorlib.dll
[Done]

Crash when trying to parse WANPPPConnection v2?

Got this crash report from a user:

Nat - Information > Initializing
OpenNat - Information > StartDiscovery
OpenNat - Information > Searching
OpenNat - Information > Searching for: UpnpSearcher
OpenNat - Verbose > UPnP Response: HTTP/1.1 200 OK
CACHE-CONTROL: max-age=1800
EXT:
LOCATION: http://192.168.0.66:8080/upnpdev/devc/uuid_3d59d5e0-1dd2-11b2-bfd6-000391c3f0fe/00
SERVER: Q77XTLN/v4.8.1-tln-11-g4207628 UPnP/1.0 BH-upnpdev/2.0
ST: urn:schemas-upnp-org:service:WANPPPConnection:2
USN: uuid:3d59d5e0-1dd2-11b2-bfd6-000391c3f0fe::urn:schemas-upnp-org:service:ContentDirectory:2

OpenNat - Information > UPnP Response: Router advertised a 'urn:schemas-upnp-org:service:WANPPPConnection:2' service!!!
OpenNat - Information > Found device at: http://192.168.0.66:8080/upnpdev/devc/uuid_3d59d5e0-1dd2-11b2-bfd6-000391c3f0fe/00
OpenNat - Information > 192.168.0.66:8080: Fetching service list
OpenNat - Error > Unhandled exception when trying to decode a device's response.
OpenNat - Error > Report the issue in https://github.com/lontivero/Open.Nat/issues
OpenNat - Error > Also copy and paste the following info:
OpenNat - Error > -- beging ---------------------------------
OpenNat - Error > Method not found: 'System.Net.HttpWebRequest System.Net.WebRequest.CreateHttp(System.Uri)'.
OpenNat - Error > Data string:
OpenNat - Error > HTTP/1.1 200 OK
CACHE-CONTROL: max-age=1800
EXT:
LOCATION: http://192.168.0.66:8080/upnpdev/devc/uuid_3d59d5e0-1dd2-11b2-bfd6-000391c3f0fe/00
SERVER: Q77XTLN/v4.8.1-tln-11-g4207628 UPnP/1.0 BH-upnpdev/2.0
ST: urn:schemas-upnp-org:service:WANPPPConnection:2
USN: uuid:3d59d5e0-1dd2-11b2-bfd6-000391c3f0fe::urn:schemas-upnp-org:service:ContentDirectory:2

OpenNat - Error > -- end ------------------------------------

about modem and router

if my modem i currently use connect to another router and that router connect to the internet
how can i port map to that router

Unhandled Object DisposedException (NetworkStream) on ARM

On an x86/x64 machine with .NET or Mono the following code works:

var discoverer = new NatDiscoverer();

var device = await discoverer.DiscoverDeviceAsync(PortMapper.Upnp, 
                     new System.Threading.CancellationTokenSource());
var ip = await device.GetExternalIPAsync();

Console.WriteLine($"The external IP Address is: {ip}");

However, the same code on ARM with .Mono (tested 4.3 and 4.6) will output an error on:

var device = await discoverer.DiscoverDeviceAsync(PortMapper.Upnp, new System.Threading.CancellationTokenSource());

Got a bad hardware address length for an AF_PACKET 16 8

And throw an exception on:

var ip = await device.GetExternalIPAsync();

Unhandled Exception:
System.ObjectDisposedException: Cannot access a disposed object.
Object name: 'System.Net.Sockets.NetworkStream'.
at System.Net.WebConnectionStream.EndWrite

This occurs on the RaspberryPI as well as other ARM devices such as the NanoPI.
Not sure whether the issue is caused by Open.NAT or Mono on ARM.

This was using the latest published NuGet package, I'll try to compile from source instead.

Raspbian crash

This might be related to the previous issue, but I don't think so.
When trying to run an application that uses Open.Nat as a dll, it fails to find an UPNP device when running on Raspbian (Rapsberry Pi 2B, up-to-date as of 2016/8/10). It works as expected on a Windows device on the same network. Output from trace:

Open.NAT Information: 0 : Start Discovery
Open.NAT Information: 0 : Searching for: UpnpSearcher
Open.NAT Information: 0 : UPnP Response: Router advertised a 'urn:schemas-upnp-org:service:WANIPConnection:1' service!!!
Open.NAT Information: 0 : Found device at: http://192.168.1.1:1780/InternetGatewayDevice.xml
Open.NAT Information: 0 : 192.168.1.1:1780: Fetching service list
Open.NAT Information: 0 : Found device at: http://192.168.1.1:1780/InternetGatewayDevice.xml
Open.NAT Error: 0 : Unhandled exception when trying to decode a device's response.
Open.NAT Error: 0 : Report the issue in https://github.com/lontivero/Open.Nat/issues
Open.NAT Error: 0 : Also copy and paste the following info:
Open.NAT Error: 0 : -- beging ---------------------------------
Open.NAT Error: 0 : The requested feature is not implemented.
Open.NAT Error: 0 : Data string:
Open.NAT Error: 0 : HTTP/1.1 200 OK
Cache-Control: max-age=300
Date: Wed, 10 Aug 2016 14:30:32 GMT
Ext:
Location: http://192.168.1.1:1780/InternetGatewayDevice.xml
Server: POSIX UPnP/1.0 DD-WRT Linux/V24
ST: urn:schemas-upnp-org:service:WANIPConnection:1
USN: uuid:E2297C1A-4B79-34A2-0D77-14FAFF984E03::urn:schemas-upnp-org:service:WANIPConnection:1

Open.NAT Error: 0 : -- end ------------------------------------
Open.NAT Information: 0 : UPnP Response: Router advertised a 'urn:schemas-upnp-org:service:WANIPConnection:1' service!!!
Open.NAT Information: 0 : Found device at: http://192.168.1.1:1780/InternetGatewayDevice.xml
Open.NAT Information: 0 : UPnP Response: Router advertised a 'urn:schemas-upnp-org:service:WANIPConnection:1' service!!!
Open.NAT Information: 0 : Found device at: http://192.168.1.1:1780/InternetGatewayDevice.xml
Open.NAT Information: 0 : UPnP Response: Router advertised a 'urn:schemas-upnp-org:service:WANIPConnection:1' service!!!
Open.NAT Information: 0 : Found device at: http://192.168.1.1:1780/InternetGatewayDevice.xml
Open.NAT Information: 0 : Searching for: PmpSearcher
Open.NAT Error: 0 : Error searching PmpSearcher - Details:
Open.NAT Error: 0 : System.Net.Sockets.SocketException: Invalid arguments
at System.Net.Sockets.Socket.SendTo_nochecks (System.Byte[] buffer, Int32 offset, Int32 size, SocketFlags flags, System.Net.EndPoint remote_end) [0x00000] in :0
at System.Net.Sockets.Socket.SendTo (System.Byte[] buffer, Int32 offset, Int32 size, SocketFlags flags, System.Net.EndPoint remote_end) [0x00000] in :0
at System.Net.Sockets.UdpClient.DoSend (System.Byte[] dgram, Int32 bytes, System.Net.IPEndPoint endPoint) [0x00000] in :0
Open.NAT Error: 0 : Error searching PmpSearcher - Details:
Open.NAT Error: 0 : System.Net.Sockets.SocketException: Invalid arguments
at System.Net.Sockets.Socket.SendTo_nochecks (System.Byte[] buffer, Int32 offset, Int32 size, SocketFlags flags, System.Net.EndPoint remote_end) [0x00000] in :0
at System.Net.Sockets.Socket.SendTo (System.Byte[] buffer, Int32 offset, Int32 size, SocketFlags flags, System.Net.EndPoint remote_end) [0x00000] in :0
at System.Net.Sockets.UdpClient.DoSend (System.Byte[] dgram, Int32 bytes, System.Net.IPEndPoint endPoint) [0x00000] in :0
Open.NAT Information: 0 : UPnP Response: Router advertised a 'urn:schemas-upnp-org:service:WANIPConnection:1' service!!!
Open.NAT Information: 0 : Found device at: http://192.168.1.1:1780/InternetGatewayDevice.xml
Open.NAT Information: 0 : UPnP Response: Router advertised a 'urn:schemas-upnp-org:service:WANIPConnection:1' service!!!
Open.NAT Information: 0 : Found device at: http://192.168.1.1:1780/InternetGatewayDevice.xml
Open.NAT Information: 0 : UPnP Response: Router advertised a 'urn:schemas-upnp-org:service:WANIPConnection:1' service!!!
Open.NAT Information: 0 : Found device at: http://192.168.1.1:1780/InternetGatewayDevice.xml
Open.NAT Information: 0 : UPnP Response: Router advertised a 'urn:schemas-upnp-org:service:WANIPConnection:1' service!!!
Open.NAT Information: 0 : Found device at: http://192.168.1.1:1780/InternetGatewayDevice.xml
Open.NAT Information: 0 : UPnP Response: Router advertised a 'urn:schemas-upnp-org:service:WANIPConnection:1' service!!!
Open.NAT Information: 0 : Found device at: http://192.168.1.1:1780/InternetGatewayDevice.xml
Open.NAT Information: 0 : UPnP Response: Router advertised a 'urn:schemas-upnp-org:service:WANIPConnection:1' service!!!
Open.NAT Information: 0 : Found device at: http://192.168.1.1:1780/InternetGatewayDevice.xml
Open.NAT Information: 0 : UPnP Response: Router advertised a 'urn:schemas-upnp-org:service:WANIPConnection:1' service!!!
Open.NAT Information: 0 : Found device at: http://192.168.1.1:1780/InternetGatewayDevice.xml
Open.NAT Information: 0 : UPnP Response: Router advertised a 'urn:schemas-upnp-org:service:WANIPConnection:1' service!!!
Open.NAT Information: 0 : Found device at: http://192.168.1.1:1780/InternetGatewayDevice.xml
Open.NAT Information: 0 : Stop Discovery
Open.NAT Information: 0 : Device not found. Common reasons:
Open.NAT Information: 0 : * No device is present or,
Open.NAT Information: 0 : * Upnp is disabled in the router or
Open.NAT Information: 0 : * Antivirus software is filtering SSDP (discovery protocol).

How to manage multilevel router?

I am a little confused, my situation is this: I have a home router and 2 laptops and 1 mobile phone is connected to that. But the home router is itself connected to a another hub. So my home router has a static public IP which is not the actual public IP of internet. My laptop has internal IP of 192.168.1.5, the router is set to static IP 10.10.152.121 and actual public IP is dynamic. I am able to forward port in my home router, but how to forward ports in that main hub where many computers are connected?

infinite recursion

trying to add a port map that already exists results in infinite recursion. CreatePortMapAsync in UpnpNatDevice.cs calls itself on error.

How to open more then one port?

Well, I can't figure out how to open more then one port. The code I used is from the example, but when run it, it opens only the last port (in my case 6626) and I THINK that it opens the two before the last one and then they stop working again but the last one is still working. My code:

    public static void Main()
    {
        OpenPort().Wait();

        Console.WriteLine("\nPress any key to exit...");
        Console.ReadKey();
    }

    private static async Task OpenPort()
    {
        var nat = new NatDiscoverer();
        var cts = new CancellationTokenSource(5000);
        var device = await nat.DiscoverDeviceAsync(PortMapper.Upnp, cts);
        var ip = await device.GetExternalIPAsync();

        Console.WriteLine("Your IP: {0}", ip);

        await device.CreatePortMapAsync(new Mapping(Protocol.Tcp, 6622, 6622, 0, "6622"));
        await device.CreatePortMapAsync(new Mapping(Protocol.Tcp, 6625, 6625, 0, "6625"));
        await device.CreatePortMapAsync(new Mapping(Protocol.Tcp, 6626, 6626, 0, "6626"));
        Console.WriteLine("Done!");
    }

Avoid the generic and unused namespace Open.

It is a bit annoying to work with IDEs when you type using Op<TAB> it gives you using Open. which is not helpful. You always want using Open.Nat. When using it in @OpenRA it is also conflicting a lot. I suggest to go with OpenNat instead.

UPnP discovery enabled in my router(Fritz!Box 7360) but openra using Open.NAT throws exception

Open.NAT Information: 0 : Start Discovery
Open.NAT Information: 0 : Searching for: UpnpSearcher
Open.NAT Information: 0 : UPnP Response: Router advertised a 'urn:schemas-upnp-org:service:WANIPConnection:1' service!!!
Open.NAT Information: 0 : Found device at: http://192.168.178.1:49000/igddesc.xml
Open.NAT Information: 0 : 192.168.178.1:49000: Fetching service list
Open.NAT Information: 0 : Found device at: http://192.168.178.1:49000/igddesc.xml
Open.NAT Error: 0 : Unhandled exception when trying to decode a device's response.
Open.NAT Error: 0 : Report the issue in https://github.com/lontivero/Open.Nat/issues
Open.NAT Error: 0 : Also copy and paste the following info:
Open.NAT Error: 0 : -- beging ---------------------------------
Open.NAT Error: 0 : The requested feature is not implemented.
Open.NAT Error: 0 : Data string:
Open.NAT Error: 0 : HTTP/1.1 200 OK
LOCATION: http://192.168.178.1:49000/igddesc.xml
SERVER: FRITZ!Box Fon WLAN 7360 UPnP/1.0 AVM FRITZ!Box Fon WLAN 7360 124.06.30
CACHE-CONTROL: max-age=1800
EXT:
ST: urn:schemas-upnp-org:service:WANIPConnection:1
USN: uuid:75802409-bccb-40e7-8e6a-5C497962507E::urn:schemas-upnp-org:service:WANIPConnection:1

Open.NAT Error: 0 : -- end ------------------------------------
Open.NAT Information: 0 : UPnP Response: Router advertised a 'urn:schemas-upnp-org:service:WANIPConnection:1' service!!!
Open.NAT Information: 0 : Found device at: http://192.168.178.1:49000/igddesc.xml
Open.NAT Information: 0 : UPnP Response: Router advertised a 'urn:schemas-upnp-org:service:WANIPConnection:1' service!!!
Open.NAT Information: 0 : Found device at: http://192.168.178.1:49000/igddesc.xml
Open.NAT Information: 0 : UPnP Response: Router advertised a 'urn:schemas-upnp-org:service:WANIPConnection:1' service!!!
Open.NAT Information: 0 : Found device at: http://192.168.178.1:49000/igddesc.xml
Open.NAT Information: 0 : Stop Discovery
Open.NAT Information: 0 : Device not found. Common reasons:
Open.NAT Information: 0 : * No device is present or,
Open.NAT Information: 0 : * Upnp is disabled in the router or
Open.NAT Information: 0 : * Antivirus software is filtering SSDP (discovery protocol).
System.AggregateException: ---> Open.Nat.NatDeviceNotFoundException: Exception of type 'Open.Nat.NatDeviceNotFoundException' was thrown.
at Open.Nat.NatDiscoverer+d__5.MoveNext () [0x00000] in :0
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x00000] in :0
at System.Runtime.CompilerServices.TaskAwaiter1[Open.Nat.NatDevice].GetResult () [0x00000] in <filename unknown>:0 at OpenRA.Network.UPnP+<DiscoverNatDevices>c__async0.MoveNext () [0x00000] in <filename unknown>:0 --- End of inner exception stack trace --- at System.Threading.Tasks.Task.Wait (Int32 millisecondsTimeout, CancellationToken cancellationToken) [0x00000] in <filename unknown>:0 at System.Threading.Tasks.Task.Wait () [0x00000] in <filename unknown>:0 at OpenRA.Game.InitializeMod (System.String mod, OpenRA.Arguments args) [0x00000] in <filename unknown>:0 --> (Inner exception 0) Open.Nat.NatDeviceNotFoundException: Exception of type 'Open.Nat.NatDeviceNotFoundException' was thrown. at Open.Nat.NatDiscoverer+<DiscoverDeviceAsync>d__5.MoveNext () [0x00000] in <filename unknown>:0 --- End of stack trace from previous location where exception was thrown --- at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x00000] in <filename unknown>:0 at System.Runtime.CompilerServices.TaskAwaiter1[Open.Nat.NatDevice].GetResult () [0x00000] in :0
at OpenRA.Network.UPnP+c__async0.MoveNext () [0x00000] in :0

DiscoverDeviceAsync exception

Forgive me if this is a total beginner's question, but I wrote the following piece of code:

    public async void ForwardPorts()
    {
        try
        {
            NatDiscoverer natDiscover = new NatDiscoverer();
            NatDevice natDevice = await natDiscover.DiscoverDeviceAsync();
            await natDevice.CreatePortMapAsync(new Mapping(Protocol.Tcp, IPAddress.Loopback, 53100, 53100, 0, "New Port Forwarded"));
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

The goal of this function is simply to forward port 53100.

I'm calling ForwardPorts() from my main function, but I get an exception: "An existing connection was forcibly closed by the remote host", do you have any idea how I can fix this or what am I doing wrong?
I would really appreciate the help, thanks in advance.

CreatePortMapAsync may not finish before the application exits

If you try to map a large number of ports (8+) a situation can occur where your application will exit before they complete. We have at least one client where the router does not appear to respond very quickly and can take up to 10-15 seconds to perform 8 create/delete portmaps.

Exiting the application early appears to stop some of the port maps from completing - Does Open.NAT queue up portmap requests or does it just send them all as the methods are called? Is it Open.NAT or the router that is the bottleneck?

Attempting to Wait() or check IsCompleted of the async methods does not help.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.