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

C# 快速檢測網絡連線狀態:P/Invoke 調用 WinINET API

     編輯:關於C語言

核心思路

通過 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 命名空間
  • 僅反映系統網絡配置狀態,不保證能訪問特定網站
  • VPN、虛擬網卡可能影響判斷準確性
  • 生產環境建議結合 Ping/HTTP 請求雙重驗證

適用場景

  • 應用啟動時的網絡前置檢查
  • 離線/在線模式自動切換
  • 網絡感知型任務調度
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved