没有端口/转发的 C# P2P [英] C# P2P without port/forwarding

查看:19
本文介绍了没有端口/转发的 C# P2P的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经制作了一个相互连接的服务器和客户端应用程序,但是我必须在路由器中打开端口才能使其工作.

I have made a server and client app which connects to each other, however I have to open ports in my router to make it work.

我可以使用不需要转发的端口吗?或者我可以应用的技术?

Are there any ports that I can use which doesn't require forwarding? Or a technique I can apply?

我想保留它 p2p 并避免在请求中间有服务器.

I want to keep it p2p and avoid having a server in the middle of requests.

推荐答案

我知道可以在这里应用两种技术.

I know of two techniques that could be applied here.

技术 1
UDP 打孔

UDP Hole Punching 使用服务器作为大厅".
您想要进行 P2P 连接的客户端首先使用 UDP 协议连接到服务器,因此客户端需要打开一个端口(洞")才能接收数据.

UDP Hole Punching uses a server as a "lobby".
The clients you want to engage a P2P connection with first connect to the server using the UDP protocol, the clients therefor require a port to be opened ("hole") to be able to receive data.

由于 UDP 是一种无连接协议,您可以将客户端设置为接受从大厅"服务器传入的数据包以及彼此之间的数据包.

Because UDP is a connection-less protocol you can set the clients up to accept packets incoming from the "lobby"-server and each other.

在两个客户端都建立连接后,服务器将为它们提供其伙伴的 IP 和匹配的hole"-port.

After both clients have established connection the server will provide them with their partner's IP and matching "hole"-port.

可以在这里的答案中找到一个非常简单的实现.

A pretty straight-forward implementation can be found in the answers here.

技巧 2
通用即插即用

这两者中我最不喜欢的,因为它要求客户端的路由器支持 uPnP 并启用它.

My least favourite of the two, as it requires the clients' routers to have uPnP support and to have it enabled.

C#.NET 中的 uPnP 可以通过包含 NATUPNPLib COM 库轻松完成
(不要忘记在参考设置中禁用嵌入互操作类型")

uPnP in C#.NET can be easily done by including the NATUPNPLib COM-library
(don't forget to disable "Embed Interop Types" in the Reference settings)

一个简单的实现是这样的:

A simple implementation would be like this:

    public const int upnp_port = 3075;

    private static UPnPNATClass pnp = new UPnPNATClass();
    private static IStaticPortMappingCollection mapc = pnp.StaticPortMappingCollection;

    public static IPAddress local_ip()
    {
        foreach (IPAddress addr in Dns.GetHostEntry(string.Empty).AddressList)
            if (addr.AddressFamily == AddressFamily.InterNetwork)
                return addr;
        return null;
    }

    public static void upnp_open()
    {
        mapc.Add(upnp_port, "UDP", upnp_port, local_ip().ToString(), true, "P2P Service Name");
    }

    public static void upnp_close()
    {
        mapc.Remove(upnp_port, "UDP");
    }

注意,这是快速编写的代码,需要忽略/优化,尤其是 local_ip() 函数,因为它可能因多个网络适配器而变得不可靠已安装.

PLEASE take note that this is quickly-written code and it will need overlooking/optimisation, definitely the local_ip() function as it can become unreliable with several network adapters installed.

这篇关于没有端口/转发的 C# P2P的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆