【发布时间】:2020-09-29 16:26:19
【问题描述】:
我正在尝试使用库 Open.NAT 创建端口映射,但收到错误
Open.Nat.MappingException: '未能创建端口映射(协议=Tcp,私有端口=12630)'
这是我的代码。哪里出了问题?
private static async Task Main()
{
NatDiscoverer discoverer = new NatDiscoverer();
NatDevice device = await discoverer.DiscoverDeviceAsync();
int port = GetAvailablePort(1000);
Mapping mapping = new Mapping(Protocol.Tcp, port, port, "Test mapping");
await device.CreatePortMapAsync(mapping);
Console.WriteLine("The external IP Address is: {0} ", await device.GetExternalIPAsync());
Console.ReadLine();
await device.DeletePortMapAsync(mapping);
}
此函数用于查找空闲端口
public static int GetAvailablePort(int startingPort)
{
List<int> portArray = new List<int>();
IPGlobalProperties properties = IPGlobalProperties.GetIPGlobalProperties();
TcpConnectionInformation[] connections = properties.GetActiveTcpConnections();
portArray.AddRange(from n in connections
where n.LocalEndPoint.Port >= startingPort
select n.LocalEndPoint.Port);
IPEndPoint[] endPoints = properties.GetActiveTcpListeners();
portArray.AddRange(from n in endPoints
where n.Port >= startingPort
select n.Port);
endPoints = properties.GetActiveUdpListeners();
portArray.AddRange(from n in endPoints
where n.Port >= startingPort
select n.Port);
portArray.Sort();
for (int i = startingPort; i < ushort.MaxValue; i++)
{
if (!portArray.Contains(i))
{
return i;
}
}
return 0;
}
【问题讨论】:
-
您的问题中暗示您的计算机实际上已连接到 NAT 路由器,并且 NAT 路由器确实支持 UPnP,并且路由器的 UPnP 支持实际上已启用。坦率地说,如果没有minimal reproducible example,实际上不可能为这样的问题提供有用的答案,但您至少需要确保网络配置也是正确的(这不是编程问题,而是网络管理问题)。
-
如果假设我的网络配置有问题,但 UTorrent 如何在我的计算机上工作并下载文件? )
-
您必须询问 UTorrent 开发人员,或者自己检查代码。也就是说,除了 UPnP 之外,还有其他方法可以导航 NAT 路由器。参见例如“打孔”。
标签: c# port portforwarding