C#驗證網絡狀態

判斷網絡狀態是否通路有兩種情況,一種是電腦有沒有接入到網絡,另一種是與某一目標主機之間是否通路。判斷是否連入網絡可以使用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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章