我正在尝试将 UDP 数据包从一个客户端发送到另一个客户端。让C1成为我用来接收数据的客户端,让C2成为将发送数据的客户端。我在做什么:
向 STUN 服务器询问两个客户端的公共 IP 地址和端口。
我通知每个客户端其他 IP 地址和公共端口。
C1在其公共地址和端口上向C2发送一个数据包,并开始侦听数据包。与此同时,C2开始发送包含我想要传输的数据的数据包。
C1只是挂起接收一个永远不会到达的数据包。我做的UDP打洞错了吗?
我正在使用同一网络上同一台计算机上的两个客户端对此进行测试,但服务器位于另一个具有公共 IP 的网络上的服务器上。我想说的是,在我测试时,两个客户端的公共地址是相同的,这是一个问题吗?
更新:
我现在知道我的路由器允许发夹。我在路由器上转发了 UDP 端口,并使用公共 IP 地址将数据包从一个客户端发送到另一个客户端。
这是我用来测试是否可以在 C# 中打孔的代码:
static UdpClient udpClient = new UdpClient(30001);
static IPAddress remoteIp;
static int remotePort;
static void Main(string[] args)
{
// Send packet to server so it can find the client's public address and port
byte[] queryServer = Encoding.UTF8.GetBytes("something");
udpClient.Send(testMsg, testMsg.Length, new IPEndPoint(IPAddress.Parse("199.254.173.154"), 30000));
// Wait for a response from the server with the other client's public address and port
IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
byte[] dataJsonBytes = udpClient.Receive(ref sender);
JObject json = JObject.Parse(Encoding.UTF8.GetString(dataJsonBytes));
remoteIp = IPAddress.Parse(json["IP"].ToString());
remotePort = Int32.Parse(json["port"].ToString());
// Start spamming the other client with packets and waiting for response
Thread sendingThread = new Thread(sendPacket);
Thread receivingThread = new Thread(receivePacket);
sendingThread.Start();
receivingThread.Start();
Console.ReadLine();
}
private static void sendPacket()
{
byte[] udpMessage = Encoding.UTF8.GetBytes("Forcing udp hole punching!!\n");
while (true)
{
udpClient.Send(udpMessage, udpMessage.Length, new IPEndPoint(remoteIp, remotePort));
Thread.Sleep(100);
}
}
private static void receivePacket()
{
IPEndPoint senderEp = new IPEndPoint(IPAddress.Any, 0);
udpClient.Client.ReceiveTimeout = 500;
while (true)
{
try
{
byte[] receivedData = udpClient.Receive(ref senderEp);
Console.Write(Encoding.UTF8.GetString(receivedData));
}
catch (Exception)
{
Console.Write("Timeout!!\n");
}
}
}
更新 2:
在@Tahlil 的帮助下,我发现我用来检查 NAT 类型的算法存在缺陷,我试图在对称 NAT 后面打孔。所以问题是没有注意到我的代码有错误......我建议对所有面临同样问题的人确定地断言 NAT 类型。
谢谢大家的帮助。