C#检查网络是否连接的方法

C# 检查网络是否连接

 在网上查到有几种方式检查网络是否连接,测试了一下,第一种方式受到ping时延的影响,在某些不支持ping的地址或者网段甚至不可用,因此建议采用方法2 

1. 调用 cmd 中的 ping 命令,分析输出信息来确定网络是否连接

 // 使用 ping 命令来判断 ,txtIP 文本框输入一个有效的远程主机 ip 

System.Diagnostics.Process proIP=new System.Diagnostics.Process();
proIP.StartInfo.FileName="cmd.exe";
proIP.StartInfo.UseShellExecute = false;
proIP.StartInfo.RedirectStandardInput = true;
proIP.StartInfo.RedirectStandardOutput = true;
proIP.StartInfo.RedirectStandardError = true;
proIP.StartInfo.CreateNoWindow = true;// 不显示 cmd 窗口
proIP.Start();
proIP.StandardInput.WriteLine("ping "+this.txtIP.Text.Trim());
proIP.StandardInput.WriteLine("exit");
string strResult=proIP.StandardOutput.ReadToEnd();
if(strResult.IndexOf("(0% loss)")!=-1)
this.txtShow.Text="Ping 通了! ";
else if(strResult.IndexOf("(100% loss)")!=-1)
this.txtShow.Text=" 无法 Ping 通! ";
else
this.txtShow.Text=" 数据有丢失! "
proIP.Close();

2. 使用InternetGetConnectedState () 函数

这个win32 API 在系统 system32 文件夹中 winInet.dll 中 ,可以用来判断是否联网和上网的方式是 Modem 还是 LAN 

//使用DllImport需导入命名空间
using System.Runtime.InteropServices;
//InternetGetConnectedState返回的状态标识位的含义:
private const int INTERNET_CONNECTION_MODEM = 1;
private const int INTERNET_CONNECTION_LAN = 2;
private const int INTERNET_CONNECTION_PROXY = 4;
private const int INTERNET_CONNECTION_MODEM_BUSY = 8;
[DllImport( "winInet.dll ")]
//声明外部的函数:
private static extern bool InternetGetConnectedState(
ref int dwFlag,
int dwReserved
);
static void Main(string[] args)
{
int dwFlag = 0;
string netstatus = "";
if (!InternetGetConnectedState(ref dwFlag, 0))
Console.WriteLine("未联网!");
else
{
if ((dwFlag & INTERNET_CONNECTION_MODEM) != 0)
netstatus += " 采用调治解调器上网 /n";
if ((dwFlag & INTERNET_CONNECTION_LAN) != 0)
netstatus += " 采用网卡上网 /n";
if ((dwFlag & INTERNET_CONNECTION_PROXY) != 0)
netstatus += " 采用代理上网 /n";
if ((dwFlag & INTERNET_CONNECTION_MODEM_BUSY) != 0)
netstatus += " MODEM被其他非INTERNET连接占用 /n";
}
Console.WriteLine(netstatus);
Console.ReadLine();
}

3.举例:

首先我们导入含有判断电脑是否联网的.dll并声明函数:

//导入判断网络是否连接的 .dll  
  [DllImport("wininet.dll", EntryPoint = "InternetGetConnectedState")]  
 //判断网络状况的方法,返回值true为连接,false为未连接  
  public extern static bool InternetGetConnectedState(out int conState, int reder);  

至此,便可直接调用InternetGetConnectedState函数实现是否联网的判断了:

int n = 0;  
 if (InternetGetConnectedState(out n, 0))  
   {  
          MessageBox.Show("yes");  
    }  
     else  
      {  
            MessageBox.Show("No");  
       } 

 



猜你喜欢

转载自blog.csdn.net/sl1990129/article/details/79405070