博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
C#使用ping命令
阅读量:4288 次
发布时间:2019-05-27

本文共 2188 字,大约阅读时间需要 7 分钟。

说明,使用ping工具

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

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

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

一、使用Ping类,效率比较高,相应快

程序集 System

命名空间:namespace System.Net.NetworkInformation

//------------使用ping类------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("失败");}

二、使用cmd命令,启动其他进程获取,等待时间长,不推荐

string host = "www.baidu.com";            Process p = new Process(); p.StartInfo.FileName = "cmd.exe";//设定程序名            p.StartInfo.UseShellExecute = false; //关闭Shell的使用            p.StartInfo.RedirectStandardInput = true;//重定向标准输入            p.StartInfo.RedirectStandardOutput = true;//重定向标准输出            p.StartInfo.RedirectStandardError = true;//重定向错误输出            p.StartInfo.CreateNoWindow = true;//设置不显示窗口            string pingrst; p.Start(); p.StandardInput.WriteLine("ping " + host); //主机或ip地址            p.StandardInput.WriteLine("exit");            string strRst = p.StandardOutput.ReadToEnd();            Console.WriteLine(strRst);            if (strRst.IndexOf("(0% loss)") != -1)            {                pingrst = "连接";            }            else if (strRst.IndexOf("Destination host unreachable.") != -1)            {                pingrst = "无法到达目的主机";            }            else if (strRst.IndexOf("Request timed out.") != -1)            {                pingrst = "超时";            }            else if (strRst.IndexOf("Unknown host") != -1)            {                pingrst = "无法解析主机";            }            else            {                pingrst = strRst;            }            p.Close();

你可能感兴趣的文章
must be str,not int
查看>>
crontab使用方法
查看>>
一元线性回归原理及python简单实现
查看>>
sql删除表中某个字段的重复数据,取较大者
查看>>
python中List和Tuple的区别
查看>>
Python中MySQL查询结果返回类型
查看>>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe4 in position 31: ordinal not in range(128)
查看>>
python2.7换行输出多个变量
查看>>
计算机工作流程
查看>>
DHCP服务器详解
查看>>
存储过程和事务区别
查看>>
c语言统计字符串中每个字符出现的次数
查看>>
python元组和列表的区别
查看>>
面试题:100个白球,100个黑球,每次取两个
查看>>
hadoop Context类
查看>>
python简介
查看>>
linux系统同时安装python2.x和3.x
查看>>
python 中的[::-1]和[:-1]
查看>>
python中eval函数和str函数
查看>>
python glob模块
查看>>