using System; using System.Collections.Generic; using System.Linq; using System.Net.NetworkInformation; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Ultron.Ngrok.Utils { public class NetworkUtils { public static string url = "www.baidu.com;www.sina.com;www.163.com;ngrok.aaqbee.com"; public static string[] urls = url.Split(new char[] { ';' }); public static FormMain fm = null; public static void RwiteLog(string message) { StringBuilder sb = new StringBuilder(NetworkUtils.fm.cmdLogTextArea.Text); NetworkUtils.fm.cmdLogTextArea.Text = sb.AppendLine(message).ToString(); NetworkUtils.fm.cmdLogTextArea.SelectionStart = fm.cmdLogTextArea.Text.Length; NetworkUtils.fm.cmdLogTextArea.ScrollToCaret(); } /// /// 检测网络连接状态 /// /// public static void CheckServeStatus(FormMain form) { Control.CheckForIllegalCrossThreadCalls = false; NetworkUtils.fm = form; int errCount = 0;//ping时连接失败个数 NetworkUtils.RwiteLog("开始检测网络..."); string checkMsg = string.Empty; if (!LocalConnectionStatus()) { checkMsg = "网络异常--无连接"; } else if (!MyPing(urls, out errCount)) { if ((double)errCount / urls.Length >= 0.3) { checkMsg = "网络异常--连接多次无响应"; } else { checkMsg = "网络不稳定"; } } else { checkMsg = "网络正常"; } NetworkUtils.RwiteLog(checkMsg); NetworkUtils.RwiteLog("网络检测结束..."); } private const int INTERNET_CONNECTION_MODEM = 1; private const int INTERNET_CONNECTION_LAN = 2; [System.Runtime.InteropServices.DllImport("winInet.dll")] private static extern bool InternetGetConnectedState(ref int dwFlag, int dwReserved); /// /// 判断本地的连接状态 /// /// private static bool LocalConnectionStatus() { System.Int32 dwFlag = new Int32(); if (!InternetGetConnectedState(ref dwFlag, 0)) { NetworkUtils.RwiteLog("本地连接状态--未连网!"); return false; } else { if ((dwFlag & INTERNET_CONNECTION_MODEM) != 0) { //NetworkUtils.RwiteLog("本地连接状态--采用调制解调器上网。"); return true; } else if ((dwFlag & INTERNET_CONNECTION_LAN) != 0) { //NetworkUtils.RwiteLog("本地连接状态--采用网卡上网。"); return true; } } return false; } /// /// Ping命令检测网络是否畅通 /// /// URL数据 /// ping时连接失败个数 /// public static bool MyPing(string[] urls, out int errorCount) { bool isconn = true; Ping ping = new Ping(); errorCount = 0; try { PingReply pr; for (int i = 0; i < urls.Length; i++) { pr = ping.Send(urls[i]); if (pr.Status != IPStatus.Success) { isconn = false; errorCount++; } //NetworkUtils.RwiteLog("Ping " + urls[i] + " " + pr.Status.ToString()); } } catch { isconn = false; errorCount = urls.Length; } //if (errorCount > 0 && errorCount < 3) // isconn = true; return isconn; } } }