C#中使用ping命令测试远程主机网络通信是否正常

说明,使用ping工具

1.可以用来查询域名是否可以访问

2.可以用来查询域名对应的ip地址

如果远程服务器允许ping命令的前提下。

解决思路:主要使用了C#提供的Ping类,效率比较高,相应快

程序集 System

命名空间:namespace System.Net.NetworkInformation

string host = "www.baidu.com";
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()));
    sbuilder.AppendLine(string.Format("RoundTrip time: {0} ", reply.RoundtripTime));
    sbuilder.AppendLine(string.Format("Time to live: {0} ", reply.Options.Ttl));
    sbuilder.AppendLine(string.Format("Don't fragment: {0} ", reply.Options.DontFragment));
    sbuilder.AppendLine(string.Format("Buffer size: {0} ", reply.Buffer.Length));
    Console.WriteLine(sbuilder.ToString());
}
else if (reply.Status == IPStatus.TimedOut)
{
    Console.WriteLine("超时");
}
else
{
    Console.WriteLine("失败");
}

posted @ 2020-10-20 23:35  rainbow70626  阅读(690)  评论(0编辑  收藏  举报