获取电脑的网络连接状态(一)InternetGetConnectedState

InternetGetConnectedState

  • 此函数获取网络状态有延时,且对网卡伤害较大
  • MSDN官方自己推荐不建议使用,不管是连网状态下还是断网情况下,获取的网络状态都有不准确的案例,如下:

  (BUG) InternetGetConnectedState API returns false result

  Detecting LAN connection using InternetGetConnectedState API doesn't work

  https://stackoverflow.com/questions/14127810/check-internet-connection-with-internetgetconnectedstate-always-true

  https://bbs.csdn.net/topics/340141699

在看下文之前,可以浏览MSDN:通过InternetGetConnectedState方法对网络状态的获取

如上InternetGetConnectedState方法介绍中

  • dwReversed必须设置为0
  • 通过输出值lpdwFlags可以获取当前网络连接的信息,通过拼装对比可以得到当前连接的网络类型,如拨号上网/局域网等
bool InternetGetConnectedState( out LPDWORD lpdwFlags, int dwReversed);

首先,添加非托管函数并调用,可以获取网络是否联网

//声明外部的函数
[DllImport("winInet.dll ")]
private static extern bool InternetGetConnectedState(ref int flag,int dwReserved);

可以通过dwFlag判断连网类型,拨号上网 or 局域网

 1         [DllImport("winInet.dll ")]
 2         private static extern bool InternetGetConnectedState(ref int flag, int dwReserved);
 3 
 4         //调制解调器上网
 5         private const int INTERNET_CONNECTION_MODEM = 1;
 6         private const int INTERNET_CONNECTION_LAN = 2;
 7         private const int INTERNET_CONNECTION_PROXY = 4;
 8         private const int INTERNET_CONNECTION_MODEM_BUSY = 8;
 9 
10         public static bool InternetGetConnectedState()
11         {
12             var dwFlag = 0;
13             if (InternetGetConnectedState(ref dwFlag, 0))
14             {
15                 if ((dwFlag & INTERNET_CONNECTION_MODEM) != 0)
16                 {
17                     //采用调制解调器上网(拨号)
18                     return true;
19                 }
20                 if ((dwFlag & INTERNET_CONNECTION_LAN) != 0)
21                 {
22                     //局域网
23                 }
24                 return true;
25             }
26             return false;
27         }

 

获取系统的网络状态与无线网的信号强度(格数)

Demo 下载

posted @ 2018-08-02 16:30  唐宋元明清2188  阅读(3665)  评论(2编辑  收藏  举报