c#檢測網絡連接問題我沒有看到好的方法,都是通過與外網(或者局域網服務器)傳遞信息檢測的。
我看些下下來了
代碼:
private void button1_Click(object sender, EventArgs e)
{
string ip;
ip = "10.1.148.1";
// string ip = "192.192.132.229";
// string strRst = CmdPing(ip);
// MessageBox.Show(strRst);
string str = CmdPingh(ip);
MessageBox.Show(str);
}
private static string CmdPing(string strIp)//方法1
{
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 -n 1 "+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;
}
public static string CmdPingh(string _strHost) //與上面的方法一樣,不同寫法而已
{
string m_strHost = _strHost;
Process process = new Process();
process.StartInfo.FileName = "cmd.exe";
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardInput = true;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = true;
process.StartInfo.CreateNoWindow = true;
string pingrst = string.Empty;
process.StartInfo.Arguments = "ping " + m_strHost + " -n 1";
process.Start();
process.StandardInput.AutoFlush = true;
string temp = "ping " + m_strHost + " -n 1" ;
process.StandardInput.WriteLine(temp);
process.StandardInput.WriteLine("exit");
string strRst = process.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;
process.Close();
return pingrst ;
}
private void button2_Click(object sender, EventArgs e)
{
jcip();
}
private void jcip()//方法2
{
Ping pingSender = new Ping ();
PingOptions options = new PingOptions ();
// Use the default Ttl value which is 128,
// but change the fragmentation behavior.
options.DontFragment = true;
// Create a buffer of 32 bytes of data to be transmitted.
string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
byte[] buffer = Encoding.ASCII.GetBytes (data);
int timeout = 120;
PingReply reply = pingSender.Send ("10.1.148.1", timeout, buffer, options);
if (reply.Status == IPStatus.Success)
{
&