Solved

C# - Release IP of specific adapter, and then renew (via DHCP) IP of that same adapter (after various tests run of course)

Posted on 2008-10-31
6
3,584 Views
Last Modified: 2013-12-17
Greetings Experts,

Ok... here is the problem that I need to resolve.

have built code in my app to find specific information about all of the installed adapters, which includes:
1) IP address
2) Adapter Description
3) MAC address of adapter.

Now, what I need to be able to do, is:

Step 1) Specify a given adapter, release the IP address which is assigned to it (assigned by DHCP)
Step 2) Run some various tests that I'm working on building (network communication tests)
Step 3) Specify the given adapter and renew the IP for that adapter via DHCP.

Factors to keep in mind:

1) This will be utilized on machines with as many as 3 network interfaces (2 physical and 1 virtual)
2) I need to be able to release & Renew ALL IP info for the specified adapter. (including IP, Mask, DNS, etc)

Thanks in advance for any code examples that I could learn from!
0
Comment
Question by:MiSheps
  • 3
6 Comments
 
LVL 3

Expert Comment

by:Blackninja2007
ID: 22856502
you could make a command line call to

ipconfig/release
&
ipconfig/renew
0
 

Author Comment

by:MiSheps
ID: 22859185

I would prefer not to use a basic windows function. I would rather do this programatically if possible, using a WMI if necessary such as ReleaseDHCPLease and RenewDHCPLease.

Though I don't know how to accomplish this.

Experts? Your help please!
0
 

Accepted Solution

by:
MiSheps earned 0 total points
ID: 22860336
Ok... I seemed to have resolved my issue, though because I am VERY new to C# programming, I would very much appreciate if an expert could have a look at my code and give any suggestions of what I can do to improve it.

I welcome ANY constructive criticism as I am just beginning to learn C# so I welcome any advice.

Here were my goals:

1) To be able to release DHCP of a specified adapter as indicated by the IP address of the given adapter.
2) To be able to renew DHCP of the specified adapter which was released in the previous step.

The purpose of this is to verify network connectivity of each individual adapter by isolating it as the only available adapter, run a test, get a success or failure, and then test the next adapter. (I have not written this test code yet).

In my case, the computers in question will have up to 3 adapters that each need to be tested individually.

So, here are the steps that I had to take to do this:

1) I had to utilize a WMI (Win32_NetworkAdapterConfiguration) to accomplish the release and renew
2) To utilize the ManagementObject, I had to first add System.Management as a reference
       A) Project - Add Reference - System.Management
3) I built the following code to handle the events

As I said, I am very new to C# programming, and I built this code from scratch. I have tested it and it seems to work well, but because I'm new to C# I don't know if it is any good or not.

I would appreciate feedback on this one to help me learn.

Thanks!

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Management;
 
namespace SpecificIPReleaseRenew
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
 
        private void Form1_Load(object sender, EventArgs e)
        {
            MyGlobalVariables.MyAdapter1IP = "192.168.1.195";
            MyGlobalVariables.MyAdapter2IP = "192.168.1.190";
            MyGlobalVariables.MyAdapter3IP = "192.168.0.152";
        }
 
        private void btnReleaseSpecificIP_Click(object sender, EventArgs e)
        {
            FindMySpecificAdapters(); //This Finds the associated card to the IP
            ReleaseMySpecificAdapter(2); //This releases the specified cards DHCP lease (Options are 1, 2, 3)
        }
 
        private void btnRenewSpecificIP_Click(object sender, EventArgs e)
        {
            RenewMySpecificAdapter(2); //This renews the specified cards DHCP lease (Options are 1, 2, 3)
        }
 
        private static void FindMySpecificAdapters() //This Searches the IP's on a computer and captures matching IP's associated object of the query.
        {
            ManagementObjectSearcher query = new ManagementObjectSearcher("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = 'TRUE'");
            ManagementObjectCollection queryCollection = query.Get();
            foreach (ManagementObject mo in queryCollection)
            {
                string[] addresses = (string[])mo["IPAddress"];
                foreach (string ipaddress in addresses)
                {
                    if (ipaddress == MyGlobalVariables.MyAdapter1IP) // If IP Address listed equals IP Address Search 1, it stores the object in a global class.
                    {
                        MyGlobalVariables.MyAdapter1 = mo;
                    }
                    if (ipaddress == MyGlobalVariables.MyAdapter2IP) // If IP Address listed equals IP Address Search 1, it stores the object in a global class.
                    {
                        MyGlobalVariables.MyAdapter2 = mo;
                    }
                    if (ipaddress == MyGlobalVariables.MyAdapter3IP) // If IP Address listed equals IP Address Search 1, it stores the object in a global class.
                    {
                        MyGlobalVariables.MyAdapter3 = mo;
                    }
                }
            }
        }
 
        private static void ReleaseMySpecificAdapter(int MyAdapterNumber) // This releases DHCP of a specified adapter by association with the above mentioned IP association. Options are 1, 2, 3)
        {
            ManagementClass objMC = new ManagementClass("Win32_NetworkAdapterConfiguration");
            ManagementObjectCollection objMOC = objMC.GetInstances();
            foreach (ManagementObject objMO in objMOC)
            {
                if (MyAdapterNumber == 1)
                {
                    if (MyGlobalVariables.MyAdapter1 == null) return; // This exits the routine if the IP for the specified adapter wasn't found in previous search to avoid throwing an error.
                    if (objMO.ToString() == MyGlobalVariables.MyAdapter1.ToString())
                    {
                        objMO.InvokeMethod("ReleaseDHCPLease", null, null);
                    }
                }
                if (MyAdapterNumber == 2)
                {
                    if (MyGlobalVariables.MyAdapter2 == null) return; // This exits the routine if the IP for the specified adapter wasn't found in previous search to avoid throwing an error.
                    if (objMO.ToString() == MyGlobalVariables.MyAdapter2.ToString())
                    {
                        objMO.InvokeMethod("ReleaseDHCPLease", null, null);
                    }
                }
                if (MyAdapterNumber == 3)
                {
                    if (MyGlobalVariables.MyAdapter3 == null) return; // This exits the routine if the IP for the specified adapter wasn't found in previous search to avoid throwing an error.
                    if (objMO.ToString() == MyGlobalVariables.MyAdapter3.ToString())
                    {
                        objMO.InvokeMethod("ReleaseDHCPLease", null, null);
                    }
                }
            }
        }
 
        private static void RenewMySpecificAdapter(int MyAdapterNumber) // This renews DHCP of a specified adapter by association with the above mentioned IP association. Options are 1, 2, 3)
        {
            ManagementClass objMC = new ManagementClass("Win32_NetworkAdapterConfiguration");
            ManagementObjectCollection objMOC = objMC.GetInstances();
            foreach (ManagementObject objMO in objMOC)
            {
                if (MyAdapterNumber == 1)
                {
                    if (MyGlobalVariables.MyAdapter1 == null) return; // This exits the routine if the IP for the specified adapter wasn't found in previous search to avoid throwing an error.
                    if (objMO.ToString() == MyGlobalVariables.MyAdapter1.ToString())
                    {
                        objMO.InvokeMethod("RenewDHCPLease", null, null);
                    }
                }
                if (MyAdapterNumber == 2)
                {
                    if (MyGlobalVariables.MyAdapter2 == null) return; // This exits the routine if the IP for the specified adapter wasn't found in previous search to avoid throwing an error.
                    if (objMO.ToString() == MyGlobalVariables.MyAdapter2.ToString())
                    {
                        objMO.InvokeMethod("RenewDHCPLease", null, null);
                    }
                }
                if (MyAdapterNumber == 3)
                {
                    if (MyGlobalVariables.MyAdapter3 == null) return; // This exits the routine if the IP for the specified adapter wasn't found in previous search to avoid throwing an error.
                    if (objMO.ToString() == MyGlobalVariables.MyAdapter3.ToString())
                    {
                        objMO.InvokeMethod("RenewDHCPLease", null, null);
                    }
                }
            }
        }
 
        private void Form1_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            Application.Exit();
        }
 
            
    }
    public class MyGlobalVariables
    {
        public static string MyAdapter1IP;
        public static string MyAdapter2IP;
        public static string MyAdapter3IP;
        public static object MyAdapter1;
        public static object MyAdapter2;
        public static object MyAdapter3;
    }
 
 
}

Open in new window

0
 

Author Comment

by:MiSheps
ID: 22860566
For the fun of it, I decided to build a stand alone application for the IP release and renew just to further learn C#.

You can download the full project in c# at the link below if you want to have a look at the code and let me know what you think.

Thanks.

http://www.mishepsbasement.com/Programming/DotNet/DragonIPReleaseAndRenew.rar


IPReleaseRenew-01.JPG
IPReleaseRenew-03.JPG
0
 
LVL 14

Expert Comment

by:jake072
ID: 22876141
Your code looks good to me.

Using the WMI is really the only way to go as there are no 100% managed solutions yet.

Well done.

Jake
0

Featured Post

MIM Survival Guide for Service Desk Managers

Major incidents can send mastered service desk processes into disorder. Systems and tools produce the data needed to resolve these incidents, but your challenge is getting that information to the right people fast. Check out the Survival Guide and begin bringing order to chaos.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
JSON Deserialize issue 6 26
Finding the IIS version 5 22
C# MVC Insert Multiple Row into DB 2 30
How to use spatial data types in SQL Server Database project 2 24
Many of us here at EE write code. Many of us write exceptional code; just as many of us write exception-prone code. As we all should know, exceptions are a mechanism for handling errors which are typically out of our control. From database errors, t…
Today I had a very interesting conundrum that had to get solved quickly. Needless to say, it wasn't resolved quickly because when we needed it we were very rushed, but as soon as the conference call was over and I took a step back I saw the correct …
Nobody understands Phishing better than an anti-spam company. That’s why we are providing Phishing Awareness Training to our customers. According to a report by Verizon, only 3% of targeted users report malicious emails to management. With compan…
The Email Laundry PDF encryption service allows companies to send confidential encrypted  emails to anybody. The PDF document can also contain attachments that are embedded in the encrypted PDF. The password is randomly generated by The Email Laundr…

829 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question