C#實現動態分配IP和釋放IP

來源:互聯網
上載者:User
最近在做一個東西,要用到動態分配IP和釋放IP。在C++下很容易就可以實現。但是由於因為網路 IP設定是要涉及到硬體,C#是沒有現成介面調用的.只能通過調用API或者是 WMI這道系統提供給我們的橋樑.主要是通過" Win32_NetworkAdapterConfiguration"這個管理類。

下面附上我寫的一個Demo,希望對需要的朋友有協助,更希望高手來拍磚。

using System;
using System.Collections.Generic;
using System.Text;
using System.Management;
using System.Management.Instrumentation;
using System.Collections;
namespace J_Queen
{
    class Program
    {
        static void Main(string[] args)
        {
            Dictionary<string, ManagementObject> allDevices = new Dictionary<string, ManagementObject>();   //儲存管理對象
            List<string> listDescription = new List<string>(); //儲存網卡描述

            //獲得管理類執行個體和管理對象
            ManagementClass classInstance = new ManagementClass( "Win32_NetworkAdapterConfiguration" );
            ManagementObjectCollection bjectCollection = classInstance.GetInstances();

            foreach (ManagementObject obj in objectCollection)
            {
                //如果沒有啟用IP設定的網路裝置則跳過
                if (!(bool)obj[ "IPEnabled" ])
                {
                    continue;
                }

               //儲存相關資訊
                allDevices.Add((string)obj[ "Description" ], obj);
                listDescription.Add((string)obj[ "Description" ]);
            }
            for (int i = 0; i < listDescription.Count;i++ )
            {
                Console.WriteLine(i.ToString() + ": " + listDescription[i]);
            }
            Console.Write( "輸入上面的數字編號(q:退出),選擇網卡:" );
            string xInput = Console.ReadLine();
            int deviceNumber;
            while (xInput != "q" )
            {
                if(!Int32.TryParse(xInput, out deviceNumber))
                {
                    Console.Write( "輸入錯誤,重新輸入: " );
                    xInput=Console.ReadLine();
                    continue;
                }
                if (deviceNumber>listDescription.Count-1 || deviceNumber<0)
                {
                    Console.Write( "輸入的編號超出範圍,重新輸入: " );
                    xInput=Console.ReadLine();
                    continue;
                }
                if (allDevices.ContainsKey(listDescription[deviceNumber]))
                {
                    Console.WriteLine( "1:表示釋放IP(Release),2:表示重新獲得IP(Renew)" );
                    string ptionInput = Console.ReadLine();
                    int option;
                    if(Int32.TryParse(optionInput, out option))
                    {
                        if(option ==1)
                        {
                            int returnValue = IpRelease((ManagementObject)allDevices[listDescription[deviceNumber]]);
                            if (returnValue<2)
                            {
                                Console.WriteLine( "成功釋放IP" );
                                Console.Write( "輸入上面網卡的數字編號(q:退出),選擇網卡:" );
                                xInput=Console.ReadLine();
                                continue;
                            }
                        }
                        else if (option == 2)
                        {
                            int returnValue = IpRenew((ManagementObject)allDevices[listDescription[option]]);
                            if (returnValue<2)
                            {
                                Console.WriteLine( "成功分配IP" );
                                Console.Write( "輸入上面網卡的數字編號(q:退出),選擇網卡:" );
                                xInput = Console.ReadLine();
                                continue;
                            }
                        }
                        else
                        {
                            Console.WriteLine( "選擇有誤" );
                            Console.Write( "輸入上面網卡的數字編號(q:退出),選擇網卡:" );
                            Console.ReadLine();
                            continue;
                        }
                    }
                }
            }
        }
        /// <summary>
        /// Function:重新分配指定網卡的IP
        /// </summary>
        /// <param name="obj">ManagementObject obj --對應網卡的管理對象</param>
        /// <returns>傳回值,整數,0和1表示成功</returns>
        public static int IpRenew(ManagementObject obj)
        {
            ManagementBaseObject utPar = null;
            utPar = obj.InvokeMethod( "RenewDHCPLease" , null, null);
            return Convert.ToInt32(outPar[ "returnValue" ]);
        }
        /// <summary>
        /// Function:釋放指定網卡IP
        /// </summary>
        /// <param name="obj">ManagementObject obj--對應網卡的管理對象</param>
        /// <returns>傳回值,整數,0和1表示成功</returns>
        public static int IpRelease(ManagementObject obj)
        {
            ManagementBaseObject utPar = null;
            utPar = obj.InvokeMethod( "ReleaseDHCPLease" , null, null);
            return Convert.ToInt32(outPar[ "returnValue" ] );
        }
    }
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.