我需要在C#编写的桌面应用程序进行端口转发端口映射在C#不工作
我用这个代码:
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是在我的Linksys路由器启用
代码正在运行,并没有给出任何错误或异常,但映射根本就没有发生。
这里是如何我测试它:
- 我有听内部端口例如应用程序8080
我手动的映射条目添加到我的路由器:
应用:HTTP,外部端口8080,内部端口8080,协议:TCP,内部IP,启用
我请求如下的URL在我的浏览器中: http:// publicIP:externalport/
- 应用程序在内部端口上收到一个套接字并回复一条消息。
我删除映射条目,并尝试添加它编程
- 相同
- 我运行执行映射
- 相同
浏览器显示跟随着消息的代码:
无法连接
火狐不能 publicIP建立与服务器的连接:externalPort
我搜索的结果进行映射的C#代码,他们看起来都一样。 为什么映射失败? 在此先感谢
你能确认你的测试方法的工作?例如,创建一个手动portforwarding和测试端口 – DarkSquirrel42
这就是我第一次做的。手动映射工作正常。 – Nina