C#中实现Ping的简单功能
关于用C#实现Ping的功能网上有很多不同的方法,但是很多代码太复杂了。这里少一点的代码来简单模拟一下这个功能。
效果如下:
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Net.NetworkInformation; namespace Bing { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { Ping p1 = new Ping(); //只是演示,没有做错误处理 PingReply reply = p1.Send(this.textBox1.Text);//阻塞方式 displayReply(reply); //显示结果 } private void displayReply(System.Net.NetworkInformation.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()); } } } }