i need to perform port forwarding in a desktop application written in C#
i used this code :
using System;
using System.Threading;
using NATUPNPLib;
namespace iSpyApplication
{
public static class NATControl
{
public static UPnPNAT NAT = new UPnPNAT();
private static IStaticPortMappingCollection _mappings;
public static IStaticPortMappingCollection Mappings
{
get
{
if (_mappings==null)
{
try
{
if (NAT.NATEventManager != null)
_mappings = NAT.StaticPortMappingCollection;
}
catch
{
}
}
return _mappings;
}
}
public static bool SetPorts(int wanPort, int lanPort)
{
bool b = false;
int i = 3;
while (Mappings == null && i > 0)
{
Thread.Sleep(2000);
i--;
}
if (Mappings != null)
{
try
{
Mappings.Remove(wanPort, "TCP");
}
catch (Exception ex)
{
// do something
}
try
{
Mappings.Add(wanPort, "TCP", lanPort, internalIP, true, "iSpy");
b = true;
}
catch (Exception ex)
{
// do something
}
}
return b;
} // method
} // class
} // namespace
UPnP is enabled in my linksys router
the code is running and not giving any errors or exceptions, however, mapping is simply not happening.
here is how i am testing it:
- i have an application that listens to an internal port e.g. 8080.
i manually add a mapping entry to my router:
application : HTTP , external port 8080 , internal port 8080, protocol: TCP , internal IP , enabled
i request the following URL in my browser: http : // publicIP : externalport /
- the application receives a socket on the internal port and replies with a message.
i remove the mapping entry and try to add it programmatically
- the same
- i run a code that performs mapping
- the same
browser displays the followin message :
Unable to connect
Firefox can't establish a connection to the server at publicIP:externalPort
i have searched for C# code that performs mapping, and they all look the same. Why would mapping fail ? Thanks in advance