在 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.R

425

被折叠的 条评论
为什么被折叠?



