Unable to add static port mapping in my c # application

I am trying to add a new static port mapping in my C # application. Because my application works as a server, and I want it to listen on port 8000.

NATUPNPLib.UPnPNATClass upnpnat = new NATUPNPLib.UPnPNATClass(); NATUPNPLib.IStaticPortMappingCollection mappings = upnpnat.StaticPortMappingCollection; mappings.Add(8000, "TCP", 8000, "192.168.1.100", true, "Local Web Server"); 

but this will not work !, The exception was the following:

The reference to the object is not installed in the instance of the object.

Can anybody help me?

This is what I'm doing: http://pietschsoft.com/post/2009/02/05/NET-Framework-Communicate-through-NAT-Router-via-UPnP.aspx

+7
source share
3 answers

You need to set the mappings to a new instance:

For example:

 var mappings = new List<Mapping>(); 

Then you can call:

 mappings.Add(8000, "TCP", 8000, "192.168.1.100", true, "Local Web Server"); 

From your edit:

 upnpnat.StaticPortMappingCollection; // this is your problem. 

The collection returns as null. Therefore, you cannot add to the collection.

You may have to:

 NATUPNPLib.IStaticPortMappingCollection mappings = new StaticPortMappingCollection(); 

From Codesleuth comment:

I believe the answer is that its router is not configured as a UPnP gateway or that it does not have permissions. StaticPortMappingCollection is null if any of these cases are true. I suggest you edit this in your answer, since you have the correct cause of the error. Checking zero first is the only way to handle the error.

+3
source

Without additional code, we can help, but if the exception is on the line you specified, it means that mappings is null and not set.

Check the code before this line to see if you are actually creating and setting the mappings variable.

According to your comment, the object returned by upnpnat.StaticPortMappingCollection is null. Check the documentation to make sure that you initialize it correctly.

+1
source

Just based on your error message, which only we have:

 var mappings = new List<Mapping>(); mappings.Add(8000, "TCP", 8000, "192.168.1.100", true, "Local Web Server"); 

After editing, possibly using:

 NATUPNPLib.IStaticPortMappingCollection mappings = new StaticPortMappingCollection(); 

Looks like you forgot to use ()

+1
source

All Articles