UDP打洞实现
我正在尝试完成UDP打洞。我的理论基于这篇文章和这篇WIKI 页面,但我在 C# 编码方面遇到了一些问题。这是我的问题:
使用此处发布的代码 我现在能够连接到远程计算机并在同一端口上侦听传入连接(将 2 个 UDP 客户端绑定到同一端口)。
由于某种原因,到同一端口的两个绑定彼此阻止接收任何数据。 我有一个 UDP 服务器来响应我的连接,因此如果我在将任何其他客户端绑定到该端口之前先连接到它,我会收到它的响应。
如果我将另一个客户端绑定到该端口,则任何一个客户端都不会收到数据。
以下是显示我的问题的 2 个代码片段。第一个连接到远程服务器以在 NAT 设备上创建规则,然后在不同的线程上启动侦听器以捕获传入数据包。然后,代码将数据包发送到本地 IP,以便侦听器能够获取它。第二个仅将数据包发送到本地 IP 以确保其正常工作。我知道这不是真正的打洞,因为我根本不使用 NAT 设备,而是将数据包发送给自己。我现在面临一个问题,如果我使用 NAT 设备外部的计算机进行连接,我认为这不会有任何不同。
[编辑]2012 年 2 月 4 日 我尝试使用网络上的另一台计算机和 WireShark(数据包嗅探器)来测试侦听器。我看到从另一台计算机传入的数据包,但侦听器 UDP 客户端 (udpServer) 或发送者 UDP 客户端 (client) 没有接收到。
[编辑]2010 年 2 月 5 日 我现在添加了一个函数调用,用于在初始发送和接收数据包后关闭第一个 UDP 客户端,仅在第二个 UDP 客户端上侦听端口。这有效,我可以在该端口上接收来自网络内部的数据包。我现在将尝试从网络外部发送和接收数据包。一旦我发现什么,我就会发布我的发现。
使用此代码,我在侦听客户端上获取数据:
static void Main(string[] args)
{
IPEndPoint localpt = new IPEndPoint(Dns.Resolve(Dns.GetHostName()).AddressList[0], 4545);
ThreadPool.QueueUserWorkItem(delegate
{
UdpClient udpServer = new UdpClient();
udpServer.ExclusiveAddressUse = false;
udpServer.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
udpServer.Client.Bind(localpt);
IPEndPoint inEndPoint = new IPEndPoint(IPAddress.Any, 0);
Console.WriteLine("Listening on " + localpt + ".");
byte[] buffer = udpServer.Receive(ref inEndPoint); //this line will block forever
Console.WriteLine("Receive from " + inEndPoint + " " + Encoding.ASCII.GetString(buffer) + ".");
});
Thread.Sleep(1000);
UdpClient udpServer2 = new UdpClient(6000);
// the following lines work and the data is received
udpServer2.Connect(Dns.Resolve(Dns.GetHostName()).AddressList[0], 4545);
udpServer2.Send(new byte[] { 0x41 }, 1);
Console.Read();
}
如果我使用以下代码,在客户端和服务器之间建立连接和数据传输后,侦听 UDP 客户端将不会收到任何内容:
static void Main(string[] args)
{
IPEndPoint localpt = new IPEndPoint(Dns.Resolve(Dns.GetHostName()).AddressList[0], 4545);
//if the following lines up until serverConnect(); are removed all packets are received correctly
client = new UdpClient();
client.ExclusiveAddressUse = false;
client.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
client.Client.Bind(localpt);
remoteServerConnect(); //connection to remote server is done here
//response is received correctly and printed to the console
ThreadPool.QueueUserWorkItem(delegate
{
UdpClient udpServer = new UdpClient();
udpServer.ExclusiveAddressUse = false;
udpServer.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
udpServer.Client.Bind(localpt);
IPEndPoint inEndPoint = new IPEndPoint(IPAddress.Any, 0);
Console.WriteLine("Listening on " + localpt + ".");
byte[] buffer = udpServer.Receive(ref inEndPoint); //this line will block forever
Console.WriteLine("Receive from " + inEndPoint + " " + Encoding.ASCII.GetString(buffer) + ".");
});
Thread.Sleep(1000);
UdpClient udpServer2 = new UdpClient(6000);
// I expected the following line to work and to receive this as well
udpServer2.Connect(Dns.Resolve(Dns.GetHostName()).AddressList[0], 4545);
udpServer2.Send(new byte[] { 0x41 }, 1);
Console.Read();
}
I am trying to accomplish UDP hole punching. I am basing my theory on this article and this WIKI page, but I am facing some issues with the C# coding of it. Here is my problem:
Using the code that was posted here I am now able to connect to a remote machine and listen on the same port for incoming connections (Bind 2 UDP clients to the same port).
For some reason the two bindings to the same port block each other from receiving any data.
I have a UDP server that responds to my connection so if I connect to it first before binding any other client to the port I get its responses back.
If I bind another client to the port no data will be received on either clients.
Following are 2 code pieces that show my problem. The first connects to a remote server to create the rule on the NAT device and then a listener is started on a different thread to capture the incoming packets. The code then sends packets to the local IP so that the listener will get it. The second only sends packets to the local IP to make sure this works. I know this is not the actual hole punching as I am sending the packets to myself without living the NAT device at all. I am facing a problem at this point, and I don't imagine this will be any different if I use a computer out side the NAT device to connect.
[EDIT] 2/4/2012
I tried using another computer on my network and WireShark (packet sniffer) to test the listener. I see the packets incoming from the other computer but are not received by the listener UDP client (udpServer) or the sender UDP client (client).
[EDIT] 2/5/2010
I have now added a function call to close the first UDP client after the initial sending and receiving of packets only living the second UDP client to listen on the port. This works and I can receive packets from inside the network on that port. I will now try to send and receive packets from outside the network. I will post my findings as soon as I find something.
Using this code I get data on the listening client:
static void Main(string[] args)
{
IPEndPoint localpt = new IPEndPoint(Dns.Resolve(Dns.GetHostName()).AddressList[0], 4545);
ThreadPool.QueueUserWorkItem(delegate
{
UdpClient udpServer = new UdpClient();
udpServer.ExclusiveAddressUse = false;
udpServer.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
udpServer.Client.Bind(localpt);
IPEndPoint inEndPoint = new IPEndPoint(IPAddress.Any, 0);
Console.WriteLine("Listening on " + localpt + ".");
byte[] buffer = udpServer.Receive(ref inEndPoint); //this line will block forever
Console.WriteLine("Receive from " + inEndPoint + " " + Encoding.ASCII.GetString(buffer) + ".");
});
Thread.Sleep(1000);
UdpClient udpServer2 = new UdpClient(6000);
// the following lines work and the data is received
udpServer2.Connect(Dns.Resolve(Dns.GetHostName()).AddressList[0], 4545);
udpServer2.Send(new byte[] { 0x41 }, 1);
Console.Read();
}
If I use the following code, after the connection and data transfer between my client and server, the listening UDP client will not receive anything:
static void Main(string[] args)
{
IPEndPoint localpt = new IPEndPoint(Dns.Resolve(Dns.GetHostName()).AddressList[0], 4545);
//if the following lines up until serverConnect(); are removed all packets are received correctly
client = new UdpClient();
client.ExclusiveAddressUse = false;
client.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
client.Client.Bind(localpt);
remoteServerConnect(); //connection to remote server is done here
//response is received correctly and printed to the console
ThreadPool.QueueUserWorkItem(delegate
{
UdpClient udpServer = new UdpClient();
udpServer.ExclusiveAddressUse = false;
udpServer.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
udpServer.Client.Bind(localpt);
IPEndPoint inEndPoint = new IPEndPoint(IPAddress.Any, 0);
Console.WriteLine("Listening on " + localpt + ".");
byte[] buffer = udpServer.Receive(ref inEndPoint); //this line will block forever
Console.WriteLine("Receive from " + inEndPoint + " " + Encoding.ASCII.GetString(buffer) + ".");
});
Thread.Sleep(1000);
UdpClient udpServer2 = new UdpClient(6000);
// I expected the following line to work and to receive this as well
udpServer2.Connect(Dns.Resolve(Dns.GetHostName()).AddressList[0], 4545);
udpServer2.Send(new byte[] { 0x41 }, 1);
Console.Read();
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
如果我理解正确的话,您正在尝试使用中介服务器进行打洞,在两个客户端之间进行点对点通信,每个客户端都位于不同的 NAT 后面?
几年前,我在 C# 中做了完全相同的事情,我还没有找到代码,但如果您愿意,我会给您一些指示:
首先,我不会在 udpclient 上使用 Connect() 函数,因为 UDP 是一个无连接协议,这个函数真正做的就是隐藏 UDP 套接字的功能。
您应该执行以下步骤:
您应该注意,nat 上使用的端口可能与您客户端电脑上使用的端口不同!服务器应将此外部端口分配给客户端。 您必须使用外部地址和外部端口来发送!
另请注意,您的 NAT 可能不支持这种端口转发。有些 NAT 将指定端口上的所有传入流量转发给您的客户端,这正是您想要的。但有些 NAT 会对传入数据包地址进行过滤,因此可能会阻止其他客户端数据包。但在使用标准个人用户路由器时,这种情况不太可能发生。
If i understand correctly, you are trying to communicate peer-to-peer between 2 clients each behind a different NAT, using a mediation server for hole punching?
Few years ago i did the exact same thing in c#, i haven't found the code yet, but ill give you some pointers if you like:
First, I wouldn't use the Connect() function on the udpclient, since UDP is a connectionless protocol, all this function really does is hide the functionality of a UDP socket.
You should perfrom the following steps:
You should note that the port used on the nat is probably not the same port as on your client pc!! The server should distribute this external port to clients. You must use the external adresses and the external ports to send to!
Also note that your NAT might not support this kind of port forwarding. Some NAT's forward all incoming traffic on a assigned port to you client, which is what you want. But some nats do filtering on the incoming packets adresses so it might block the other clients packets. This is unlikely though when using a standard personal user router.
编辑:经过更多测试后,除非我启用 UPnP,否则这似乎对我根本不起作用。因此,我在这里写的很多内容可能对您有用,但许多人没有启用 UPnP(因为这是一个安全风险),因此它对他们不起作用。
这是一些使用 PubNub 作为中继服务器的代码:)。我不建议在未经测试的情况下使用此代码,因为它并不完美(我不确定它是否安全或正确的做事方式?idk我不是网络专家)但它应该给你一个想法做什么。到目前为止,它至少在我的业余爱好项目中对我有用。它缺少的东西是:
因此,首先,您需要一种获取外部和本地 IP 的方法。这是获取本地 IP 的代码:
这是通过尝试一些旨在返回外部 IP 的网站来获取外部 IP 的代码
现在我们需要找到一个开放端口并将其转发到外部端口。如上所述,我使用了 Open.NAT。首先,在查看注册的 UDP 后,将您认为适合应用程序使用的端口列表放在一起端口。以下是一些示例:
现在我们可以循环遍历它们,并希望找到一个未使用的端口转发:
现在是 PubNub 中继服务器代码(P2PPeer 将在下面定义)。这里有很多内容,所以我不会真正解释它,但希望代码足够清晰,可以帮助您理解正在发生的事情
,这是一个 P2PPeer
最后,这是我的所有用法:
我愿意接受评论和问题,如果这里的某些做法不好或不起作用,请随时提供反馈。我的代码在翻译过程中引入了一些错误,我最终会在这里修复这些错误,但这至少应该让您知道该怎么做。
Edit: After a lot more testing this doesn't seem to work at all for me unless I enable UPnP. So a lot of the things I wrote here you may find useful but many people don't have UPnP enabled (because it is a security risk) so it will not work for them.
Here is some code using PubNub as a relay server :). I don't recommend using this code without testing because it is not perfect (I'm not sure if it is even secure or the right way to do things? idk I'm not a networking expert) but it should give you an idea of what to do. It at least has worked for me so far in a hobby project. The things it is missing are:
So first of all, you need a way to get your external and local IPs. Here is code for getting your local IP:
And here is some code for getting your external IP via trying a few websites that are designed to return your external IP
Now we need to find an open port and forward it to an external port. As mentioned above I used Open.NAT. First, you put together a list of ports that you think would be reasonable for your application to use after looking at registered UDP ports. Here are a few for example:
Now we can loop through them and hopefully find one that is not in use to use port forwarding on:
Now for the PubNub relay server code (P2PPeer will be defined later below). There is a lot here so I'm not really gonna explain it but hopefully the code is clear enough to help you understand what is going on
And here is a P2PPeer
Finally, here are all my usings:
I'm open to comments and questions, feel free to give feedback if something here is bad practice or doesn't work. A few bugs were introduced in translation from my code that I'll fix here eventually but this should at least give you the idea of what to do.
您是否尝试过使用异步函数,这里是一个如何让它工作的示例,它可能需要一些工作才能使其 100% 正常工作:
我希望这会有所帮助。
Have you tried using the Async functions, here is a example of how you might get it to work it may need a bit of work to make it 100% functional:
I hope this helps.
更新:
第一个绑定的 UdpClient 就是 Windows 将发送传入数据包的 UdpClient。在您的示例中,尝试将设置侦听线程的代码块移至顶部。
您确定问题不仅仅是接收线程仅为处理单个接收而编写吗?尝试将接收线程替换为如下所示。
Update:
Whichever of the UdpClients binds first is the one that will be sent incoming packets by Windows. In your example try moving the code block that sets up the listening thread to the top.
Are you sure the problem is not just that the receive thread is only written to handle a single receive? Try replacing the receive thread with as below.
抱歉上传这么大的代码,但我想这非常清楚地解释了事情是如何工作的,并且可能非常有用。如果您对此代码有疑问,请告诉我。
注意:
UdpClient
与服务器进行通信,Server.cs
Client.cs
Demo.cs< /em>
Protocol.cs
我不确定这种方法有多好,也许像 protobuf 这样的东西可以做得更好
Sorry for uploading such a huge piece of code, but i guess this is very clearly explains how things work, and may be really useful. If you will have issues with this code, please let me know.
Note:
UdpClient
'sServer.cs
Client.cs
Demo.cs
Protocol.cs
I'm not sure how good this approach, maybe something like protobuf can do it better