C # Implementation to dynamically allocate IP and release IP

Source: Internet
Author: User
Tags exit count readline

Recently doing a thing to use to dynamically allocate IP and release IP. It's easy to implement in C + +. However, because the network IP settings are related to hardware, C # is not a ready-made interface call. The bridge can only be provided to us by invoking the API or the WMI system. It is mainly through the "Win32_NetworkAdapterConfiguration" of this management class.

Attached below I wrote a demo, I hope to need a friend to help, but also want to master to shoot bricks.

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> (); Save Management Objects


list<string> listdescription = new list<string> (); Save Network card Description


//Get management class instances and Management Objects


ManagementClass classinstance = new ManagementClass ("Win32_NetworkAdapterConfiguration");


managementobjectcollection bjectcollection = classinstance.getinstances ();


foreach (ManagementObject obj in objectcollection)


      {


///If no IP settings are enabled for network devices skip


if (!) ( BOOL) obj["ipenabled"])


        {


continue;


        }


//Storage related information


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 ("Enter the number above the digital number (Q: Exit), select the network card:");


String xinput = Console.ReadLine ();


int devicenumber;


while (xinput!= "q")


      {


if (! Int32.TryParse (XInput, out devicenumber))


        {


console.write ("Input error, reenter:");


Xinput=console.readline ();


continue;


        }


if (devicenumber>listdescription.count-1 | | devicenumber<0)


        {


Console.Write ("Enter the number out of range, re-enter:");


Xinput=console.readline ();


continue;


        }


if (Alldevices.containskey (listdescription[devicenumber))


        {


Console.WriteLine ("1: Free IP (Release), 2: means to regain 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 ("Successfully released IP");


Console.Write ("Enter the number of the above network card number (Q: Exit), select the network card:");


Xinput=console.readline ();


continue;


              }


            }


else if (option = 2)


            {


int returnvalue = Iprenew ((managementobject) alldevices[listdescription[option]);


if (returnvalue<2)


              {


Console.WriteLine ("Successfully assigned IP");


Console.Write ("Enter the number of the above network card number (Q: Exit), select the network card:");


xinput = Console.ReadLine ();


continue;


              }


            }


Else


            {


Console.WriteLine ("Wrong Choice");


Console.Write ("Enter the number of the above network card number (Q: Exit), select the network card:");


Console.ReadLine ();


continue;


            }


          }


        }


      }


    }


///<summary>


///Function: Reassign IP
for the specified network adapter

///</summary>


///<param name= "obj" >managementobject obj--management object corresponding to the NIC </param>


///<returns> return values, integers, 0 and 1 for Success </returns>


public static int iprenew (ManagementObject obj)


    {


Managementbaseobject utpar = null;


Utpar = obj. InvokeMethod ("RenewDHCPLease", NULL, NULL);


return Convert.ToInt32 (outpar["returnvalue");


    }


///<summary>


///Function: Frees the specified network adapter IP


///</summary>


///<param name= "obj" >managementobject obj--the management object corresponding to the NIC </param>


///<returns> return values, integers, 0 and 1 for success </returns>


public static int iprelease (ManagementObject obj)


    {


Managementbaseobject utpar = null;


Utpar = obj. InvokeMethod ("ReleaseDHCPLease", NULL, NULL);


return Convert.ToInt32 (outpar["returnvalue");


    }


  }


}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.