这里我写的是一个窗体程序。首先添加textbox,listbox,button控件,其中textbox录入域名或IP,listbox显示结果. ( gLp:V4Zj
在button1_click事件键入 |Rb S@+
private void button1_Click(object sender, EventArgs e) hIurY
{ LJaP%-V0
Ping p1 = new Ping(); //只是演示,没有做错误处理 hdc S&\
PingReply reply = p1.Send(this.textBox1.Text);//阻塞方式 displayReply(reply); //显示结果 } private void displayReply(PingReply reply) //显示结果 3Te7R lJa
{ =7/J4(uwd
StringBuilder sbuilder ; zw r]1*|&
if (reply.Status == IPStatus.Success) 0a( "<
{ ~Gv&G/4
sbuilder = new StringBuilder(); q "N]bG
sbuilder.Append(string.Format("Address: {0} ", reply.Address.ToString ())); b"_[a.]
sbuilder.Append(string.Format("RoundTrip time: {0} ", reply.RoundtripTime)); Z1[ay&t2
sbuilder.Append(string.Format("Time to live: {0} ", reply.Options.Ttl)); Z fiVS
sbuilder.Append(string.Format("Don't fragment: {0} ", reply.Options.DontFragment)); ;_,>}&)da
sbuilder.Append(string.Format("Buffer size: {0} ", reply.Buffer.Length)); "f=$Ubx
listBox1.Items.Add(sbuilder.ToString()); {qdM}Ot#]-
} #Z3;oQ
}[nextpage] 9uV"-T,
也可以做异步的处理,修改button1_click,并添加PingCompletedCallBack方法 U f!95"Hu
private void button1_Click(object sender, EventArgs e) zGqudcx$5
{ uo\ P2"_&
Ping p1 = new Ping(); )N$xY%^`
p1.PingCompleted += new PingCompletedEventHandler(this.PingCompletedCallBack);//设置PingCompleted事件处理程序 _<?j&>
p1.SendAsync(this.textBox1.Text, null); =?$YZo1
} sHE?U(hm7
private void PingCompletedCallBack(object sender, PingCompletedEventArgs e) CB { F)GAQSBqt
if (e.Cancelled) .]@5RVe
{ v+EmLb)p
listBox1.Items.Add("Ping Canncel"); i*Hm0 9c
return; [=V 9N } 5v6qSSH
if (e.Error != null) '{k16/jT
{ ^CLoTsV7:
listBox1.Items.Add(e.Error.Message); (3E?Gz#p
return; "CTAgf?5
} Z*uZ\=o}1
StringBuilder sbuilder; A ;je=T
PingReply reply = e.Reply; %ok$l>)H
if (reply.Status == IPStatus.Success) k5O&a #,ra
{ FX Qi 5
sbuilder = new StringBuilder(); L3\@CH':
sbuilder.Append(string.Format("Address: {0} ", reply.Address.ToString())); 2l:?SAIO.
sbuilder.Append(string.Format("RoundTrip time: {0} ", reply.RoundtripTime)); K+lC`
sbuilder.Append(string.Format("Time to live: {0} ", reply.Options.Ttl)); qJW7^ O-5
sbuilder.Append(string.Format("Don't fragment: {0} ", reply.Options.DontFragment)); o lwe}d
sbuilder.Append(string.Format("Buffer size: {0} ", reply.Buffer.Length)); coTke6,0
listBox1.Items.Add(sbuilder.ToString()); D~IGWKDp
} +( }