C#使用ping命令的两个例子
程序员文章站
2023-12-21 09:25:34
方法一:调用cmd 的ping命令
private static string cmdping(string strip)
{
pro...
方法一:调用cmd 的ping命令
private static string cmdping(string strip) { 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 " + strip); p.standardinput.writeline("exit"); string strrst = p.standardoutput.readtoend(); 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(); return pingrst; }
方法二:使用c#中的ping 类
private void displayreply(pingreply reply) //显示结果 { ping p1 = new ping(); //只是演示,没有做错误处理 pingreply reply = p1.send("填写ip地址"); 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)); response.write(sbuilder.tostring()); } else if (reply.status == ipstatus.timeout) { response.write("超时"); }else{ response.write("失败"); }