在 C# 開發中,經常需要判斷電腦目前是否連上網路。雖然 .NET Framework 提供了 NetworkInterface.GetIsNetworkAvailable() 等方法,但有時候我們需要更底層、更精確的判斷方式,例如透過 Windows 系統自帶的 WinINET API 來檢測真實的網際網路連線狀態。本文將詳細介紹如何使用 P/Invoke 呼叫 wininet.dll 中的 InternetGetConnectedState 函式,並提供完整可執行的程式碼範例。
InternetGetConnectedState 是 Windows WinINET 库提供的經典函式,專門用於檢測本機是否已建立網際網路連線。它的簽名如下:
[DllImport("wininet.dll")]
private extern static bool InternetGetConnectedState(
out int connectionDescription,
int reservedValue
);
INTERNET_CONNECTION_MODEM、INTERNET_CONNECTION_LAN、INTERNET_CONNECTION_PROXY 等),若不需要知道具體連線類型,可傳遞一個暫存變數接收即可。System.Runtime.InteropServices 命名空間,否則會發生編譯錯誤。connectionDescription 的輸出容器(例如 int desc = 0;)。InternetGetConnectedState(out desc, 0) 並接收回傳的布林值。using System;
using System.Runtime.InteropServices;
namespace NetworkCheckDemo
{
public class InternetChecker
{
// 匯入 WinINET API
[DllImport("wininet.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern bool InternetGetConnectedState(out int connectionDescription, int reservedValue);
///
/// 檢查是否已連線至網際網路
///
/// true=已連線, false=未連線
public static bool IsConnected()
{
int description = 0;
return InternetGetConnectedState(out description, 0);
}
///
/// 取得詳細連線類型描述(選用)
///
public static string GetConnectionType()
{
int description = 0;
bool connected = InternetGetConnectedState(out description, 0);
if (!connected) return "離線";
// 解析旗標(可依需求擴充)
System.Text.StringBuilder sb = new System.Text.StringBuilder();
if ((description & 0x01) != 0) sb.Append("MODEM ");
if ((description & 0x02) != 0) sb.Append("LAN ");
if ((description & 0x04) != 0) sb.Append("PROXY ");
if ((description & 0x10) != 0) sb.Append("OFFLINE ");
return sb.Length > 0 ? sb.ToString().Trim() : "未知類型";
}
}
class Program
{
static void Main(string[] args)
{
bool online = InternetChecker.IsConnected();
Console.WriteLine($"網路狀態:{(online ? "已連線 (Online)" : "未連線 (Offline)")}");
if (online) Console.WriteLine($"連線類型:{InternetChecker.GetConnectionType()}");
Console.ReadKey();
}
}
}
wininet.dll,跨平台專案(如 .NET Core / .NET 5+ 執行於 Linux/macOS)無法直接使用,需改用 System.Net.NetworkInformation 或 Ping 方式替代。true 代表系統認為有可用的網路介面且已連線,但不保證能連上特定網站(如防火牆攔截、DNS 故障等情況),建議搭配實際 HTTP 請求驗證。透過 InternetGetConnectedState 我們能快速、低成本地判斷 Windows 系統層面的網路連線狀態,適合用於桌面應用程式啟動檢查、離線模式切換等場景。若需跨平台支援,請改用 .NET 內建的 NetworkInterface 或 HttpClient 發送測試請求的方式。