本文介绍了C# 如何在没有端口转发的情况下通过 UDP 发送字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要类似的东西:

        var client = new UdpClient();
        IPEndPoint ep = new IPEndPoint(IPAddress.Parse("23.114.44.195"), 11000);
        client.Connect(ep);

        byte[] data = Encoding.ASCII.GetBytes("test");
        client.Send(data, data.Length);

侦听器在 PORT: 11000 的那个 IP 上运行,但我不想在我的路由器中转发端口(因为我想发布这个应用程序).


The listener runs on that IP at PORT: 11000, but i don't want to port forward in my router (because I want to publish this app).

那么,问题来了:如何在没有端口转发的情况下通过 UDP 发送字符串?

So, here is the question: How to send string via UDP without Port Forwarding?

推荐答案

您可以使用 NAT 打孔,不需要手动配置端口转发.这是很简单的技术.请注意,远程端点(接收方)也应该实现它,而不仅仅是发送方.

You can use NAT hole punching, which doesn't require manual port forwarding configuration. It's quite simple technique. Please note that remote endpoint (receiver) should implement it too, not just sender.

在最简单的情况下,它的作用是:

In the simplest case, it works as:

[sender] <-> |internet| <-> [remote router with NAT] <-> [receiver]

请注意 sender 不在 NAT 之后.

Please note sender is not behind NAT.

senderIP:portXreceiverIP:portY 打一个洞:sender 绑定到 portX 并等待来自 receiver 的通信初始化.receiver 绑定到 portY 并向 senderIP:portX 发送一个虚拟数据包.sender 从包中获取receiverIP(实际上是它的路由器IP)和portY,然后将有意义的数据发送到这个地址.NAT 记住与 senderIP:portX 的通信来自 receiver 的本地 IP 和 portY,因此所有数据都来自 senderIP:portX 到路由器的 portY 将被重定向到 receiver 的本地 IP.

To punch a hole from senderIP:portX to receiverIP:portY:sender binds to portX and waits for communication initialisation from receiver. receiver binds to portY and sends a dummy packet to senderIP:portX. sender gets receiverIP (which is actually its router IP) and portY from the package and now sends meaningful data to this address. NAT remembered that communication with senderIP:portX was going from receivers local IP and portY, so all data coming from senderIP:portX to the router's portY will be redirected to receivers local IP.

对于 senderreceiver 都在 NAT 之后的情况,您需要一个集合服务器,详情请查看链接.

For the case when both sender and receiver are behind NATs, you need a rendezvous server, for details check the link.

这篇关于C# 如何在没有端口转发的情况下通过 UDP 发送字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-27 10:23