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

C# 動態釋放與續約 IP 位址(WMI 實作)

     編輯:關於C語言

背景

C# 無直接操作網路設定的 API,需透過 WMI Win32_NetworkAdapterConfiguration 管理類別實現 IP 釋放與續約。

核心程式碼

using System;
using System.Collections.Generic;
using System.Management;

namespace NetworkTool {
    class Program {
        static void Main(string[] args) {
            var allDevices = new Dictionary<string, ManagementObject>();
            var descriptions = new List<string>();

            // 取得啟用 IP 的網卡
            ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
            foreach (ManagementObject obj in mc.GetInstances()) {
                if ((bool)obj["IPEnabled"]) {
                    string desc = (string)obj["Description"];
                    allDevices[desc] = obj;
                    descriptions.Add(desc);
                }
            }

            // 列出供選擇
            for (int i = 0; i < descriptions.Count; i++)
                Console.WriteLine($"{i}: {descriptions[i]}");

            Console.Write("選擇網卡編號 (q 退出):");
            string input = Console.ReadLine();

            while (input != "q") {
                if (int.TryParse(input, out int idx) && idx >= 0 && idx < descriptions.Count) {
                    Console.WriteLine("1: 釋放 IP  2: 續約 IP");
                    string opt = Console.ReadLine();
                    if (int.TryParse(opt, out int action)) {
                        ManagementObject nic = allDevices[descriptions[idx]];
                        int ret = (action == 1) ? ReleaseIP(nic) : RenewIP(nic);
                        if (ret < 2) Console.WriteLine(action == 1 ? "釋放成功" : "續約成功");
                    }
                }
                Console.Write("選擇網卡編號 (q 退出):");
                input = Console.ReadLine();
            }
        }

        static int RenewIP(ManagementObject obj) {
            var outParams = obj.InvokeMethod("RenewDHCPLease", null, null);
            return Convert.ToInt32(outParams["ReturnValue"]);
        }

        static int ReleaseIP(ManagementObject obj) {
            var outParams = obj.InvokeMethod("ReleaseDHCPLease", null, null);
            return Convert.ToInt32(outParams["ReturnValue"]);
        }
    }
}

說明

  • 回傳值 0 或 1 表示成功
  • 需專案參考 System.Management.dll
  • 需管理員權限執行
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved