【发布时间】:2012-11-06 04:59:57
【问题描述】:
我需要在用 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
在我的 linksys 路由器中启用了 UPnP
代码正在运行并且没有给出任何错误或异常,但是,映射根本没有发生。
这是我的测试方法:
- 我有一个监听内部端口的应用程序,例如8080。
-
我手动将映射条目添加到我的路由器:
应用程序:HTTP,外部端口 8080,内部端口 8080,协议:TCP,内部 IP,启用
我在浏览器中请求以下 URL: http : // publicIP : 外部端口 /
- 应用程序在内部端口上接收到一个套接字并回复一条消息。
我删除映射条目并尝试以编程方式添加它
- 一样
- 我运行了一个执行映射的代码
- 一样
-
浏览器显示以下消息:
无法连接
Firefox 无法与服务器建立连接 公共IP:外部端口
我搜索了执行映射的 C# 代码,它们看起来都一样。 为什么映射会失败? 在此先感谢
【问题讨论】:
-
您能确认您的测试方法有效吗?例如,创建手动端口转发并测试该端口
-
这就是我首先做的。手动映射工作正常。
标签: c# upnp portforwarding