点击这里给我发消息 点击这里给我发消息

c#下实现ping操作

添加时间:2014-7-18
    相关阅读: 程序

这里我写的是一个窗体程序。首先添加textbox,listbox,button控件,其中textbox录入域名或IP,listbox显示结果.

  在button1_click事件键入

  private void button1_Click(object sender, EventArgs e)

  {

  Ping p1 = new Ping(); //只是演示,没有做错误处理

  PingReply reply = p1.Send(this.textBox1.Text);//阻塞方式 displayReply(reply); //显示结果 } private void displayReply(PingReply reply) //显示结果

  {

  StringBuilder sbuilder ;

  if (reply.Status == IPStatus.Success)

  {

  sbuilder = new StringBuilder();

  sbuilder.Append(string.Format("Address: {0} ", reply.Address.ToString ()));

  sbuilder.Append(string.Format("RoundTrip time: {0} ", reply.RoundtripTime));

  sbuilder.Append(string.Format("Time to live: {0} ", reply.Options.Ttl));

  sbuilder.Append(string.Format("Don't fragment: {0} ", reply.Options.DontFragment));

  sbuilder.Append(string.Format("Buffer size: {0} ", reply.Buffer.Length));

  listBox1.Items.Add(sbuilder.ToString());

  }

  }[nextpage]

  也可以做异步的处理,修改button1_click,并添加PingCompletedCallBack方法

  private void button1_Click(object sender, EventArgs e)

  {

  Ping p1 = new Ping();

  p1.PingCompleted += new PingCompletedEventHandler(this.PingCompletedCallBack);//设置PingCompleted事件处理程序

  p1.SendAsync(this.textBox1.Text, null);

  }

  private void PingCompletedCallBack(object sender, PingCompletedEventArgs e)

  {

  if (e.Cancelled)

  {

  listBox1.Items.Add("Ping Canncel");

  return;

  }

  if (e.Error != null)

  {

  listBox1.Items.Add(e.Error.Message);

  return;

  }

  StringBuilder sbuilder;

  PingReply reply = e.Reply;

  if (reply.Status == IPStatus.Success)

  {

  sbuilder = new StringBuilder();

  sbuilder.Append(string.Format("Address: {0} ", reply.Address.ToString()));

  sbuilder.Append(string.Format("RoundTrip time: {0} ", reply.RoundtripTime));

  sbuilder.Append(string.Format("Time to live: {0} ", reply.Options.Ttl));

  sbuilder.Append(string.Format("Don't fragment: {0} ", reply.Options.DontFragment));

  sbuilder.Append(string.Format("Buffer size: {0} ", reply.Buffer.Length));

  listBox1.Items.Add(sbuilder.ToString());

  }

  }

咨询热线:020-85648757 85648755 85648616 0755-27912581 客服:020-85648756 0755-27912581 业务传真:020-32579052
广州市网景网络科技有限公司 Copyright◎2003-2008 Veelink.com. All Rights Reserved.
广州商务地址:广东省广州市黄埔大道中203号(海景园区)海景花园C栋501室
= 深圳商务地址:深圳市宝源路华丰宝源大厦606
研发中心:广东广州市天河软件园海景园区 粤ICP备05103322号 工商注册