首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> C# >> 關於C#

C# 使用 WinINET API 檢測網路連線狀態完整教學

     編輯:關於C#

前言

在 C# 開發中,經常需要判斷電腦目前是否連上網路。雖然 .NET Framework 提供了 NetworkInterface.GetIsNetworkAvailable() 等方法,但有時候我們需要更底層、更精確的判斷方式,例如透過 Windows 系統自帶的 WinINET API 來檢測真實的網際網路連線狀態。本文將詳細介紹如何使用 P/Invoke 呼叫 wininet.dll 中的 InternetGetConnectedState 函式,並提供完整可執行的程式碼範例。

核心 API 介紹:InternetGetConnectedState

InternetGetConnectedState 是 Windows WinINET 库提供的經典函式,專門用於檢測本機是否已建立網際網路連線。它的簽名如下:

[DllImport("wininet.dll")]
private extern static bool InternetGetConnectedState(
    out int connectionDescription,
    int reservedValue
);

參數說明

  • connectionDescription (out int):輸出參數,回傳連線類型的旗標組合(如 INTERNET_CONNECTION_MODEM、INTERNET_CONNECTION_LAN、INTERNET_CONNECTION_PROXY 等),若不需要知道具體連線類型,可傳遞一個暫存變數接收即可。
  • reservedValue (int):保留參數,必須設為 0。

回傳值

  • true:目前已連上網路 (On Line)
  • false:目前離線狀態 (Off Line)

實作步驟

  1. 在程式碼頂端引用 System.Runtime.InteropServices 命名空間,否則會發生編譯錯誤。
  2. 定義一個整數變數作為 connectionDescription 的輸出容器(例如 int desc = 0;)。
  3. 呼叫 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();
        }
    }
}

常見問題與注意事項

  • 僅適用於 Windows 平台:此 API 依賴 wininet.dll,跨平台專案(如 .NET Core / .NET 5+ 執行於 Linux/macOS)無法直接使用,需改用 System.Net.NetworkInformation 或 Ping 方式替代。
  • 權限問題:一般使用者權限即可呼叫,不需要管理員權限。
  • 回傳值的解讀:true 代表系統認為有可用的網路介面且已連線,但不保證能連上特定網站(如防火牆攔截、DNS 故障等情況),建議搭配實際 HTTP 請求驗證。

總結

透過 InternetGetConnectedState 我們能快速、低成本地判斷 Windows 系統層面的網路連線狀態,適合用於桌面應用程式啟動檢查、離線模式切換等場景。若需跨平台支援,請改用 .NET 內建的 NetworkInterface 或 HttpClient 發送測試請求的方式。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved