判断网络状态是否通路有两种情况,一种是电脑有没有接入到网络,另一种是与某一目标主机之间是否通路。判断是否连入网络可以使用wininet.dll;而判断与某一目标主机是否通路时暂时想到的就只有ping命令了。
1.判断网络通路:
view plaincopy to clipboardprint?
[DllImport("wininet.dll")]
private extern static bool InternetGetConnectedState(out int connectionDescription, int reservedValue);
private bool isConnected()
{
int I = 0;
bool state = InternetGetConnectedState(out I, 0);
return state;
}
[DllImport("wininet.dll")]
private extern static bool InternetGetConnectedState(out int connectionDescription, int reservedValue);
private bool isConnected()
{
int I = 0;
bool state = InternetGetConnectedState(out I, 0);
return state;
}
判断isConnected就可以了
2.判断与某目标主机是否通路:
view plaincopy to clipboardprint?
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 -n 1 " + strIp); //-n 1 : 向目标IP发送一次请求
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("not find") != -1)
{
pingrst = "无法解析主机";
}
else
{
pingrst = strRst;
}
p.Close();
return pingrst;
}
本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/redhaste/archive/2009/04/24/4107679.aspx