本文主要是介绍c#: 检测网路连通性,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
环境:
-window 10 x64 专业版
-vs2019
-.net 控制台 ; .net framework4.0;
参照:https://www.cnblogs.com/fuchongjundream/p/3853820.html
一、先看运行效果
二、代码
InternectCheckHelper.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.NetworkInformation;
using System.Security.Policy;
using System.Text;namespace ConsoleApp9
{public class InternectCheckHelper{private static List<string> _interneturls = null;private static List<string> _localneturls = null;static InternectCheckHelper(){_interneturls = new List<string>() { "www.baidu.com", "www.sina.com", "www.cnblogs.com" };_localneturls = new List<string>();for (int i = 0; i < 11; i++){_localneturls.Add($"192.168.{i}.1");_localneturls.Add($"10.0.{i}.1");_localneturls.Add($"172.16.{i}.1");}}/// <summary>/// 设置用于检测互联网连通性的地址,如:www.baidu.com,程序检测时会执行ping命令检测/// </summary>/// <param name="urls"></param>public static void SetInternetPingUrls(params string[] urls){if (urls != null && urls.Length > 0){_interneturls = new List<string>();_interneturls.AddRange(urls);}}/// <summary>/// 设置用于检测局域网连通性的地址,如:192.168.0.1,程序检测时会执行ping命令检测/// </summary>/// <param name="urls"></param>public static void SetLocalnetPingUrls(params string[] urls){if (urls != null && urls.Length > 0){_localneturls = new List<string>();_localneturls.AddRange(urls);}}/// <summary>/// 检测是否能连接到互联网/// </summary>/// <returns></returns>public static bool CanConnectInternect(){//先检查本地网络状态if (!LocalConnectionStatus()) return false;//再检查互联网连通状态if (!NetConnectionStatus(_interneturls)) return false;return true;}public static string GetConnectType(){System.Int32 dwFlag = new Int32();if (!InternetGetConnectedState(ref dwFlag, 0)){return "未连网";}else{if ((dwFlag & INTERNET_CONNECTION_MODEM) != 0){return "调制解调器";}else if ((dwFlag & INTERNET_CONNECTION_LAN) != 0){return "网卡";}}return "未连网";}public static bool CanConnectLocalnet(){//先检查本地网络状态if (!LocalConnectionStatus()) return false;//再检查内网连通状态if (!NetConnectionStatus(_localneturls)) return false;return true;}#region 网络检测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);/// <summary>/// 判断本地的连接状态/// </summary>/// <returns></returns>private static bool LocalConnectionStatus(){System.Int32 dwFlag = new Int32();if (!InternetGetConnectedState(ref dwFlag, 0)) return false;else{if ((dwFlag & INTERNET_CONNECTION_MODEM) != 0) return true;else if ((dwFlag & INTERNET_CONNECTION_LAN) != 0) return true;}return false;}private static bool NetConnectionStatus(List<string> urls){Ping ping = new Ping();try{PingReply pr;for (int i = 0; i < urls.Count; i++){pr = ping.Send(urls[i]);if (pr.Status == IPStatus.Success) return true;}return false;}catch (Exception ex){try{string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "logs");if (!Directory.Exists(path)) Directory.CreateDirectory(path);path = Path.Combine(path, $"{DateTime.Now.ToString("yyyy-MM-dd")}.inetchk.log");File.AppendAllText(path, $"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")} err:{ex?.Message} {ex?.StackTrace}");}catch { }return false;}}#endregion}
}
调用: Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.NetworkInformation;
using System.Text;namespace ConsoleApp9
{class Program{static void Main(string[] args){if (InternectCheckHelper.CanConnectInternect()){Console.WriteLine("能连接到互联网.");}else{Console.WriteLine("不能连接到互联网");}if (InternectCheckHelper.CanConnectLocalnet()){Console.WriteLine("能连接到局域网.");}else{Console.WriteLine("不能连接到局域网.");}Console.WriteLine($"连接类型:{InternectCheckHelper.GetConnectType()}");Console.ReadKey();}}
}
这篇关于c#: 检测网路连通性的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!