方法一:
方法二:using System.Net.NetworkInformation; Ping ping = new Ping(); PingReply reply = ping.Send("IP 位置"); if (reply.Status == IPStatus.Success) { MessageBox.Show(string.Format("IP:{0}連接成功!", reply.Address)); } else { MessageBox.Show(string.Format("IP:{0}連接失敗!", reply.Address)); }
public partial class Form8 : Form { private string host; private Ping ping; private byte[] buffer = Encoding.ASCII.GetBytes("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"); private int timeout = 5000;// Wait 5秒 private bool runThread; Thread pingThread; public Form8() { InitializeComponent(); CheckForIllegalCrossThreadCalls = false; } private void btnPing_Click(object sender, EventArgs e) { this.richTextBox1.Clear(); host = this.tbHost.Text; if (host.Length == 0) throw new Exception("請輸入主機名稱 or IP位置"); ping = new Ping(); //同步模式 /*PingReply reply = ping.Send(host, timeout, buffer); display(reply);*/ //異步模式, 不可直接用在form, 必須獨立 thread runThread = true; pingThread = new Thread(this.sendPing); pingThread.Start(); } private void sendPing() { AutoResetEvent waiter = new AutoResetEvent(false); ping.PingCompleted += new PingCompletedEventHandler(pingCompletedCallback); PingOptions options = new PingOptions(64, true); while (runThread) { ping.SendAsync(host, timeout, buffer, options, waiter); waiter.WaitOne(); Thread.Sleep(1000);//當前線程 sleep } } public void pingCompletedCallback(object sender, PingCompletedEventArgs e) { if (e.Cancelled) { addLine("退出Ping"); ((AutoResetEvent)e.UserState).Set();//繼續主線程 } if (e.Error != null) { addLine("Ping 失敗"); addLine(e.Error.ToString()); ((AutoResetEvent)e.UserState).Set(); } PingReply reply = e.Reply; display(reply); ((AutoResetEvent)e.UserState).Set(); } public void display(PingReply reply) { if (reply == null) return; addLine("ping 狀態:" + reply.Status); if (reply.Status == IPStatus.Success) { addLine("位置:" + reply.Address.ToString()); addLine("時間:" + reply.RoundtripTime); addLine("TTL:" + reply.Options.Ttl); addLine("不許可數據損壞:" + reply.Options.DontFragment); addLine("緩衝區:" + reply.Buffer.Length); } } private void addLine(string data, bool newLine = true) { richTextBox1.AppendText(data + Environment.NewLine); } private void Form8_FormClosing(object sender, FormClosingEventArgs e) { pingThread.Abort(); } private void btnStop_Click(object sender, EventArgs e) { runThread = false; // Use the Join method to block the current thread until the object's thread terminates. pingThread.Join(); } }