首先,我初学,不会使用,求各位源代码和注解以作参考,学习学习
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.NetworkInformation;
using System.Text;
using System.Threading.Tasks;
using System.Timers;
namespace ping
{
class Program
{
static void Main(string[] args)
{
System.Timers.Timer timer = new System.Timers.Timer();
timer.Enabled = true;
timer.Interval = 1000; //执行间隔时间,单位为毫秒; 这里实际间隔为1秒
timer.Start();
timer.Elapsed += new System.Timers.ElapsedEventHandler(test);
//Console.Readkey()保持Console窗口不关闭,否则,该程序执行后一闪就关闭,不会等1分钟的时间。
Console.ReadKey();
}
private static void test(object source, ElapsedEventArgs e)
{
string host = "180.101.49.58";
Ping p1 = new Ping();
PingReply reply = p1.Send(host); //发送主机名或Ip地址
StringBuilder sbuilder;
if (reply.Status == IPStatus.Success)
{
sbuilder = new StringBuilder();
sbuilder.AppendLine(string.Format("Address: {0} ", reply.Address.ToString())); //获取发送Internet控制消息协议(ICMP)回送答复的主机地址。
//sbuilder.AppendLine(string.Format("RoundTrip time: {0} ", reply.RoundtripTime)); //获取发送Internet 控制消息协议(ICMP)回送请求并接收相应ICMP回送答复消息所用的毫秒数。
//sbuilder.AppendLine(string.Format("Time to live: {0} ", reply.Options.Ttl)); //获取或设置在丢弃System.Net.NetworkInformation.Ping 数据之前可以转发该数据的路由节点数。
//sbuilder.AppendLine(string.Format("Don't fragment: {0} ", reply.Options.DontFragment)); //获取或设置System.Boolean 值,该值控制发送到远程主机的数据的分段。
//sbuilder.AppendLine(string.Format("Buffer size: {0} ", reply.Buffer.Length)); //获取Internet控制消息协议(ICMP)回送答复消息中收到的数据缓冲区。
Console.Write(sbuilder.ToString());
}
else if (reply.Status == IPStatus.TimedOut)
{
Console.WriteLine("超时");
}
else
{
Console.WriteLine("失败");
}
string host2 = "www.baidu.com";
Ping p2 = new Ping();
PingReply reply1 = p1.Send(host2); //发送主机名或Ip地址
StringBuilder sbuilder1;
if (reply1.Status == IPStatus.Success)
{
sbuilder1 = new StringBuilder();
sbuilder1.AppendLine(string.Format("Address: {0} ", reply1.Address.ToString()));
//sbuilder1.AppendLine(string.Format("RoundTrip time(时间): {0} ", reply1.RoundtripTime));
//sbuilder1.AppendLine(string.Format("Time to live(TTL): {0} ", reply1.Options.Ttl));
//sbuilder1.AppendLine(string.Format("Don't fragment: {0} ", reply1.Options.DontFragment));
//sbuilder1.AppendLine(string.Format("Buffer size(字节): {0} ", reply1.Buffer.Length));
Console.WriteLine(sbuilder1.ToString());
}
else if (reply1.Status == IPStatus.TimedOut)
{
Console.WriteLine("超时");
}
else
{
Console.WriteLine("失败");
}
}
}
}