System.Net.NetworkInformationTextBox(輸入 IP/域名)、ListBox(顯示結果)、Button(觸發)適用於簡單工具、測試腳本,UI 會在等待回應期間凍結。
using System;
using System.Net.NetworkInformation;
using System.Text;
using System.Windows.Forms;
namespace PingDemo
{
public partial class MainForm : Form
{
public MainForm() { InitializeComponent(); }
private void btnSyncPing_Click(object sender, EventArgs e)
{
using (var ping = new Ping())
{
try
{
PingReply reply = ping.Send(txtTarget.Text.Trim());
DisplayReply(reply);
}
catch (Exception ex)
{
lstResult.Items.Add($"錯誤:{ex.Message}");
}
}
}
private void DisplayReply(PingReply reply)
{
if (reply.Status != IPStatus.Success)
{
lstResult.Items.Add($"失敗:{reply.Status}");
return;
}
var sb = new StringBuilder();
sb.AppendLine($"位址:{reply.Address}");
sb.AppendLine($"往返時間:{reply.RoundtripTime} ms");
sb.AppendLine($"TTL:{reply.Options?.Ttl}");
sb.AppendLine($"Don't Fragment:{reply.Options?.DontFragment}");
sb.AppendLine($"緩衝區大小:{reply.Buffer?.Length} bytes");
lstResult.Items.Add(sb.ToString());
}
}
}
採用事件型非同步模式(EAP),適合 WinForms/WPF 即時回饋場景。
private void btnAsyncPing_Click(object sender, EventArgs e)
{
var ping = new Ping();
ping.PingCompleted += PingCompletedCallback;
// 第二個參數為 userToken,可傳遞自定義物件
ping.SendAsync(txtTarget.Text.Trim(), null);
}
private void PingCompletedCallback(object sender, PingCompletedEventArgs e)
{
var ping = sender as Ping;
ping.PingCompleted -= PingCompletedCallback; // 解除訂閱防止記憶體洩漏
ping.Dispose();
if (e.Cancelled)
{
lstResult.Items.Add("已取消");
return;
}
if (e.Error != null)
{
lstResult.Items.Add($"例外:{e.Error.Message}");
return;
}
DisplayReply(e.Reply); // 復用同步版的顯示邏輯
}
var options = new PingOptions
{
Ttl = 64,
DontFragment = true
};
byte[] buffer = Encoding.ASCII.GetBytes("測試資料");
PingReply reply = ping.Send(target, 3000, buffer, options); // 3 秒逾時
Ping.SendPingAsync// 更簡潔的 Task-based 非同步
PingReply reply = await ping.SendPingAsync("google.com", 5000);
DisplayReply(reply);
DestinationHostUnreachable 或 TimedOut。Invoke / Dispatcher.Invoke。