C#实现动态分配IP和释放IP

原文地址: http://soft.zdnet.com.cn/software_zone/2008/0805/1039556.shtml

 

      最近在做一个东西,要用到动态分配IP和释放IP。在C++下很容易就可以实现。但是由于因为网络IP设置是要涉及到硬件,C#是没有现成接口调用的。只能通过调用API或者是WMI这道系统提供给我们的桥梁.主要是通过"Win32_NetworkAdapterConfiguration"这个管理类。

   希望对需要的朋友有帮助,更希望高手来拍砖。

 

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" ] );
        }
    }
}

本文件是C#代码片断 public Form1() { InitializeComponent(); } int i = 0; int j = 0; string[] proxys; #region 改变代理 [DllImport("wininet.dll", SetLastError = true)] private static extern bool InternetSetOption(IntPtr hInternet, int dwOption, IntPtr lpBuffer, int lpdwBufferLength); /// public void RefreshIESettings(string strProxy) { const int INTERNET_OPTION_PROXY = 38; const int INTERNET_OPEN_TYPE_PROXY = 3; Struct_INTERNET_PROXY_INFO struct_IPI; // Filling in structure struct_IPI.dwAccessType = INTERNET_OPEN_TYPE_PROXY; struct_IPI.proxy = Marshal.StringToHGlobalAnsi(strProxy); struct_IPI.proxyBypass = Marshal.StringToHGlobalAnsi("local"); // Allocating memory IntPtr intptrStruct = Marshal.AllocCoTaskMem(Marshal.SizeOf(struct_IPI)); // Converting structure to IntPtr Marshal.StructureToPtr(struct_IPI, intptrStruct, true); bool iReturn = InternetSetOption(IntPtr.Zero, INTERNET_OPTION_PROXY, intptrStruct, Marshal.SizeOf(struct_IPI)); } #endregion private void Form1_Load(object sender, EventArgs e) { proxys = File.ReadAllLines("C:/proxy.txt"); } private void timer1_Tick(object sender, EventArgs e) { if (i < proxys.Length) { label2.Text = proxys[i]; label9.Text = i.ToString(); label3.Text = "waiting..."; RefreshIESettings(proxys[i]); webBrowser1.Navigate("http://www.imwq.net"); timer1.Enabled = false; i++; } else { timer1.Enabled = false; button1.Text = "结束"; } } private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) { label3.Text = "ok..."; timer1.Enabled = true; } private void button1_Click(object sender, EventArgs e) { timer1.Enabled = true; } } struct Struct_INTERNET_PROXY_INFO { public int dwAccessType; public IntPtr proxy; public IntPtr proxyBypass; };
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值