c#检查网络是否连接互联网的方法

您所在的位置:网站首页 如何检查网络连接是否正常 c#检查网络是否连接互联网的方法

c#检查网络是否连接互联网的方法

2024-05-08 10:24| 来源: 网络整理| 查看: 265

 

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

 

1 //导入命名空间 2 using System.Net.NetworkInformation; 3 4 5 /// 6 /// Ping命令检测网络是否畅通 7 /// 8 /// URL地址 9 /// 是否ping通 10 public static bool ChinarPing(string url) 11 { 12 Ping ping = new Ping(); 13 try 14 { 15 PingReply pr = ping.Send(url); 16 if (pr.Status == IPStatus.Success) 17 { 18 return true; 19 } 20 else 21 { 22 return false; 23 } 24 } 25 26 catch 27 { 28 isSucceed = false; 29 } 30 }

 

 

 

 

2. 使用InternetGetConnectedState () 函数

 

public const int INTERNET_CONNECTION_MODEM = 0x01; //调制解调器连接到 Internet public const int INTERNET_CONNECTION_LAN = 0x02; //局域网网卡连接到 Internet public const int INTERNET_CONNECTION_PROXY = 0x04; //代理服务器连接到 Internet private const int INTERNET_RAS_INSTALLED = 0x08; //已安装 RAS public const int INTERNET_CONNECTION_OFFLINE = 0x14; //脱机模式 public const int INTERNET_CONNECTION_CONFIGURED = 0x40; //具有到 Internet 的有效连接,但它当前可能连接也可能不连接

 

 

 

 

//使用DllImport需导入命名空间 using System.Runtime.InteropServices; //导入判断网络是否连接的 .dll //判断网络状况的方法,返回值true为连接,false为未连接 [DllImport("wininet.dll")] private extern static bool InternetGetConnectedState(int Description, int ReservedValue); /// /// 用于检查网络是否可以连接互联网,true表示连接成功,false表示连接失败 /// /// public static bool IsConnectInternet() { int Description = 0; return InternetGetConnectedState(Description, 0); } /// /// 判断本地的连接状态 /// private static bool IsConnectedInternet() { int dwFlag = new int(); if (!InternetGetConnectedState(ref dwFlag, 0)) { PrintR("当前没有联网,请您先联网后再进行操作!"); if ((dwFlag & 0x14) == 0) return false; Debug.LogWarning("本地系统处于脱机模式。"); return false; } else { if ((dwFlag & 0x01) != 0) { Print("调制解调器上网。"); return true; } else if ((dwFlag & 0x02) != 0) { Print("网卡上网。"); return true; } else if ((dwFlag & 0x04) != 0) { Print("代理服务器上网。"); return true; } else if ((dwFlag & 0x40) != 0) { Print("虽然可以联网,但可能链接也可能不连接。"); return true; } } return false; }

 

 

 

 

 



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3