【问题标题】:How do you ping a remote server with UDP如何使用 UDP ping 远程服务器
【发布时间】:2021-11-04 11:47:53
【问题描述】:

所以我正在尝试设置框架以创建一个不和谐机器人,该机器人将检查用户专用服务器是否打开并相应地更新消息。我目前在本地网络中的另一台计算机上运行 Minecraft 和 Valheim 服务器。

我尝试使用 Microsoft 提供的 Ping 类,但它无法 ping Valheim 服务器。 Valheim 似乎正在使用 UDP 协议,所以我尝试使用 UdpClient 类来发送消息,但它仍然处于“WaitingForActivation”状态,我不知道要发送什么来获得响应。

是否有服务器识别为 ping 的标准消息?我已经能够 ping 具有 UDP 模式的站点的端口,所以我确定它是打开的并且能够被 ping。

这是我用来尝试 ping 的代码

UdpClient udpPing = new UdpClient();
Byte[] sentBytes = Encoding.ASCII.GetBytes("Ping");

udpPing.Connect(servers[i].ip, servers[i].port);
udpPing.Send(sentBytes,sentBytes.Length);

IPEndPoint remoteEndPoint = new IPEndPoint(IPAddress.Any, servers[i].port);
Task<UdpReceiveResult> result = udpPing.ReceiveAsync();

bool error = false;
for (int y = 0; result.Status == TaskStatus.WaitingForActivation && !error; y++)
{
    if(y == tryLimit)
    {
        error = true;
    }
}
udpPing.Close();```

【问题讨论】:

    标签: c# sockets .net-core discord udp


    【解决方案1】:

    为什么不使用Ping class?从该页面:

    using System;
    using System.Net;
    using System.Net.NetworkInformation;
    using System.Text;
    
    namespace Examples.System.Net.NetworkInformation.PingTest
    {
        public class PingExample
        {
            // args[0] can be an IPaddress or host name.
            public static void Main (string[] args)
            {
                Ping pingSender = new Ping ();
                PingOptions options = new PingOptions ();
    
                // Use the default Ttl value which is 128,
                // but change the fragmentation behavior.
                options.DontFragment = true;
    
                // Create a buffer of 32 bytes of data to be transmitted.
                string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
                byte[] buffer = Encoding.ASCII.GetBytes (data);
                int timeout = 120;
                PingReply reply = pingSender.Send (args[0], timeout, buffer, options);
                if (reply.Status == IPStatus.Success)
                {
                    Console.WriteLine ("Address: {0}", reply.Address.ToString ());
                    Console.WriteLine ("RoundTrip time: {0}", reply.RoundtripTime);
                    Console.WriteLine ("Time to live: {0}", reply.Options.Ttl);
                    Console.WriteLine ("Don't fragment: {0}", reply.Options.DontFragment);
                    Console.WriteLine ("Buffer size: {0}", reply.Buffer.Length);
                }
            }
        }
    }
    

    【讨论】:

    • 正如我在问题中所述,我无法让 Ping 类与 Valheim 服务器一起使用。我认为这是因为 Valheim 使用 UDP 而不是 TCP 协议
    • 标准 ping 不使用 UDP 或 TCP,而是使用 ICMP。
    猜你喜欢
    • 1970-01-01
    • 2016-08-10
    • 1970-01-01
    • 1970-01-01
    • 2018-01-06
    • 1970-01-01
    • 2011-09-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多