C#检测是否有网络连接
C#检测是否有网络连接
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; //使用DllImport需导入命名空间 using System.Runtime.InteropServices; using System.Net.NetworkInformation; namespace CheckNetwork { class Program { static void Main(string[] args) { bool isConn = IsConnectedInternet(); bool isConn2= IsConnectedToInternet2(); Console.ReadKey(); } #region 第二种方法 public static bool IsConnectedToInternet2() { string host ="www.baidu.com"; bool result = false; Ping p = new Ping(); try { PingReply reply = p.Send(host, 3000); if (reply.Status == IPStatus.Success) return true; } catch (Exception ex) { } return result; } #endregion //导入判断网络是否连接的 .dll //判断网络状况的方法,返回值true为连接,false为未连接 [DllImport("wininet.dll")] private extern static bool InternetGetConnectedState( ref int Description, int ReservedValue); /// <summary> /// 用于检查网络是否可以连接互联网,true表示连接成功,false表示连接失败 /// </summary> /// <returns></returns> public static bool IsConnectInternet() { int Description = 0; return InternetGetConnectedState(ref Description, 0); } /// <summary> /// 判断本地的连接状态 /// </summary> private static bool IsConnectedInternet() { int dwFlag = new int(); if (!InternetGetConnectedState( ref dwFlag, 0)) { Console.WriteLine("当前没有联网,请您先联网后再进行操作!"); if ((dwFlag & 0x14) == 0) return false; System.Diagnostics.Debug.WriteLine("本地系统处于脱机模式。"); return false; } else { if ((dwFlag & 0x01) != 0) { Console.WriteLine("调制解调器上网。"); return true; } else if ((dwFlag & 0x02) != 0) { Console.WriteLine("网卡上网。"); return true; } else if ((dwFlag & 0x04) != 0) { Console.WriteLine("代理服务器上网。"); return true; } else if ((dwFlag & 0x40) != 0) { Console.WriteLine("虽然可以联网,但可能链接也可能不连接。"); return true; } } return false; } } }
代码示例收集自网络。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
2019-07-25 vs看源代码
2017-07-25 数据库原理