方法1:使用C#中的ping类
private void ping(string strDestIp)
{
Ping myPing = new Ping();
PingOptions myOptions = new PingOptions();
myOptions.DontFragment = true;
string data = "abcdefghijklmnopqrstuvwxy123456";
byte[] buff = Encoding.ASCII.GetBytes(data);
PingReply myPingReply = myPing.Send(strDestIp, 500, buff, myOptions);
if (myPingReply.Status == IPStatus.Success)
{
Console.WriteLine("ping" + strDestIp + "成功");
}
else
{
Console.WriteLine("ping" + strDestIp + "失败");
}
}
方法二:
调用cmd 的ping命令
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
|
private
static
string
CmdPing(
string
strIp)
{
Process p =
new
Process(); p.StartInfo.FileName =
"cmd.exe"
;
p.StartInfo.UseShellExecute =
false
;
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)//中文操作系统和英文操作系统显示不一样,英文loss,中文 丢失
{
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;
}
|