在 C# 中,可以使用 System.Net.NetworkInformation
命名空间中的 Ping
类来实现 Ping 命令的功能。下面是一个简单的示例,演示如何使用 Ping
类来发送 ICMP 请求并获取响应。
示例代码
Csharp
深色版本
1using System;
2using System.Net.NetworkInformation;
3
4class Program
5{
6 static void Main()
7 {
8 // 目标主机的 IP 地址或域名
9 string host = "www.example.com";
10
11 // 创建 Ping 对象
12 using (Ping ping = new Ping())
13 {
14 // 创建 Ping 选项
15 PingOptions options = new PingOptions();
16
17 // 创建缓冲区
18 byte[] buffer = new byte[32];
19
20 // 创建 Ping 回调函数
21 PingCompletedCallback callback = new PingCompletedCallback(PingCompletedCallbackMethod);
22
23 // 发送 Ping 请求
24 ping.PingCompleted += callback;
25 ping.SendAsync(host, 1000, buffer, options, null);
26 }
27
28 Console.WriteLine("Press any key to exit.");
29 Console.ReadKey();
30 }
31
32 static void PingCompletedCallbackMethod(object sender, PingCompletedEventArgs e)
33 {
34 // 检查是否有异常
35 if (e.Error != null)
36 {
37 Console.WriteLine("Error: " + e.Error.Message);
38 }
39 else
40 {
41 // 获取 PingReply 对象
42 PingReply reply = e.Reply;
43
44 // 输出结果
45 Console.WriteLine("Address: " + reply.Address);
46 Console.WriteLine("Roundtrip time: " + reply.RoundtripTime.ToString());
47 Console.WriteLine("Time to live: " + reply.Options.Ttl);
48 Console.WriteLine("Don't fragment: " + reply.Options.DontFragment);
49 Console.WriteLine("Buffer size: " + reply.Buffer.Length);
50 }
51 }
52}
代码解释
-
导入命名空间:
- 导入
System.Net.NetworkInformation
命名空间,它包含Ping
类和其他相关的类。
- 导入
-
创建 Ping 对象:
- 使用
using
语句创建Ping
对象,确保对象在使用完之后被正确地释放。
- 使用
-
设置 Ping 选项:
- 创建
PingOptions
对象,用于设置 Ping 请求的选项,如生存时间(TTL)和是否允许分片。
- 创建
-
创建缓冲区:
- 创建一个字节数组作为 Ping 请求的数据缓冲区。通常这个缓冲区很小,例如 32 字节。
-
设置回调函数:
- 创建一个
PingCompletedCallback
委托类型的回调函数,该函数将在 Ping 请求完成后被调用。
- 创建一个
-
发送 Ping 请求:
- 使用
Ping
对象的SendAsync
方法发送 Ping 请求。此方法接受目标地址、超时时间、缓冲区、Ping 选项和一个用户提供的对象参数。 - 用户提供的对象参数在这里被设置为
null
,但在实际应用中,可以传递额外的数据,以便在回调函数中使用。
- 使用
-
处理 Ping 结果:
- 在回调函数中,根据
PingCompletedEventArgs
对象来判断是否有异常发生,如果没有异常,则输出 Ping 的结果。
- 在回调函数中,根据