问题描述
我在C#中有一个函数可以找到一个开放端口:
I have a function in C# that finds an open port :
var listener = new TcpListener(IPAddress.Loopback, 0);
listener.Start();
int port = ((IPEndPoint)listener.LocalEndpoint).Port;
listener.Stop();
return port;
打开该端口后,是否可以检查该端口是否可以用UPnP映射?因为我要尝试转发它,所以我想提前知道它是否会失败.
Is it possible, once I have opened that port, to check if this port can be mapped with UPnP? Because I'm about to try to forward it and I want to know in advance if it's going to fail.
推荐答案
是的,您当然可以,但是我必须警告您,不幸的是,许多家用Internet路由器和网关对UPnP协议的实现不佳,并且并不总是能正常工作很好.很烂,但这就是我们生活的世界.:)
Yes you certainly can, however I must warn you that unfortunately many home internet routers and gateways have a poor implementation of the UPnP protocol and it doesn't always work very well. It sucks but that's the world we live in. :)
UPnP协议规范非常庞大和复杂,因此我强烈建议您使用框架.有两个很棒的开源C#框架可以使用:
The UPnP protocol specification is very big and complex so I strongly suggest you use a framework. There are a couple of great open source C# frameworks to use:
- Mono.NAT
- Open.NAT
我个人建议 Open.NAT ,因为它具有更现代的异步实现.
I personally recommend Open.NAT as it has a more modern async implementation.
以下是使用Open.NAT尝试打开或映射UDP端口1600的示例:
Here is an example of using Open.NAT to attempt to open or map UDP port 1600:
public static void Main(string[] args) {
// Setup and initialize Open.NAT:
NatUtility.PortMapper = Upnp; // Search only for Upnp devices
NatUtility.TraceSource.Switch.Level = SourceLevels.Information;
NatUtility.DeviceFound += DeviceFound;
NatUtility.Initialize();
// Start looking for UPnP devices:
NatUtility.StartDiscovery();
while(true) {}
}
// This method is called every time a new UPnP device is found:
private static async void DeviceFound (object sender, DeviceEventArgs args) {
var deviceIP = await device.GetExternalIPAsync();
Console.WriteLine("Found a UPnP device with IP " + deviceIP);
Console.WriteLine("Attempting to map UDP port 1600...");
await device.CreatePortMapAsync(new Mapping(Protocol.Udp, 1600, 1600, 10000, "Open.Nat Testing"));
}
简单!当然,您可以做更多的事情,例如向路由器询问其当前已映射的所有UPnP端口.您应该查看Open.NAT文档.
Simple! You can of course do a lot more such as asking the router for all the UPnP ports it currently has mapped. You should check the Open.NAT documentation for that.
这篇关于检查端口是否可以使用upnp映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!