《C#验证网络状态》由会员分享,可在线阅读,更多相关《C#验证网络状态(4页珍藏版)》请在金锄头文库上搜索。
1、首先引入命名空间:using System.Runtime.InteropServices;再定义如下: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;在按钮里写以下代码:i
2、f (IsConnected()MessageBox.Show(状态:网络畅通!);elseMessageBox.Show(状态:与目标网络无连接!);判断网络状态是否通路有两种情况,一种是电脑有没有接入到网络,另一种是与某一 目标主机之间是否通路。判断是否连入网络可以使用winin et.dll;而判断与某一目标主 机是否通路时暂时想到的就只有ping命令了。1.判断网络通路:view plaincopy to clipboardprint?DllImport(wininet.dll)private extern static bool InternetGetConnectedState(o
3、ut 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() i
4、nt 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.Start
5、Info.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.WriteLi
6、ne(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 = 无法解析主机;elsepingrst = strRst;p.Close();return pingrst;