通過 P/Invoke 調用 wininet.dll 中的 InternetGetConnectedState 函數,無需發送數據包即可快速判斷系統網絡連接狀態。
using System;
using System.Runtime.InteropServices;
namespace NetworkCheck
{
public class InternetConnection
{
// P/Invoke 簽名
[DllImport(\"wininet.dll\", CharSet = CharSet.Auto)]
private static extern bool InternetGetConnectedState(
out int connectionDescription,
int reservedValue
);
///
/// 檢查是否連接互聯網
///
public static bool IsConnected()
{
int desc = 0;
return InternetGetConnectedState(out desc, 0);
}
///
/// 獲取詳細連接類型
///
public static string GetConnectionType()
{
int desc = 0;
bool connected = InternetGetConnectedState(out desc, 0);
if (!connected) return \"離線\";
// 解析 connectionDescription 位標誌
var types = new List<string>();
if ((desc & 0x1) != 0) types.Add(\"調制解調器\");
if ((desc & 0x2) != 0) types.Add(\"局域網\");
if ((desc & 0x4) != 0) types.Add(\"代理服務器\");
if ((desc & 0x10) != 0) types.Add(\"RAS 已安裝\");
if ((desc & 0x20) != 0) types.Add(\"離線模式\");
if ((desc & 0x40) != 0) types.Add(\"已配置\");
return types.Count > 0 ? string.Join(\", \", types) : \"未知類型\";
}
}
}
// 簡單檢查
if (InternetConnection.IsConnected())
Console.WriteLine(\"在線\");
else
Console.WriteLine(\"離線\");
// 獲取詳細類型
Console.WriteLine($\"連接方式: {InternetConnection.GetConnectionType()}\");
System.Runtime.InteropServices 命名空間