• 0

[C#] Enabling DHCP on NIC through WMI


Question

I was testing SwitchNetConfig (code available at: http://www.codeproject.com/csharp/OazSwitchNetConfig.asp) but it's not working correctly...

I create a profile, select a nic card, select to obtain IP from DHCP but it's not correctly enabled. The result of the action will be red outline. What I want to do is in the blue outline. (I'm talking about the image attached)

Here's the code that tries to enable DHCP:

public static void SetDHCP( string nicName )
		{
			ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
			ManagementObjectCollection moc = mc.GetInstances();

			foreach(ManagementObject mo in moc)
			{
				// Make sure this is a IP enabled device. Not something like memory card or VM Ware
				if( (bool)mo["IPEnabled"] )
				{
					if( mo["Caption"].Equals( nicName ) )
					{
						ManagementBaseObject newDNS = mo.GetMethodParameters( "SetDNSServerSearchOrder" );
						newDNS[ "DNSServerSearchOrder" ] = null;
						ManagementBaseObject enableDHCP = mo.InvokeMethod( "EnableDHCP", null, null);
						ManagementBaseObject setDNS = mo.InvokeMethod( "SetDNSServerSearchOrder", newDNS, null);
					}
				}
			}
		}

post-22268-1164509949_thumb.jpg

Link to comment
Share on other sites

11 answers to this question

Recommended Posts

  • 0

Worked fine for me. Are you sure you're selecting the right instance of your NIC? 2 different ones show up in my list for the same card. It worked on one binding, but not the other.

Link to comment
Share on other sites

  • 0

Just tested and here's what I've found out.

I have 4 items in my network connections, 2 of them disabled cuase I don't really use them (1394 Connection, Cisco Systems VPN Adapter). The other is my laptop's wireless card and ethernet card. It worked for the ethernet card, but for the wireless card, it happens has the screenshot above... I don't get it...

Link to comment
Share on other sites

  • 0

I tested this on several other laptops and it seems to happen to all of them the same thing... One thing to note, is that, this only seem to happen to wireless network cards. One curiosity though, is that the ones I tested, are all the same: Intel® PRO/Wireless 2200BG

Can't anyone help me out with this? No one understands this WMI thing that could help me out?

Link to comment
Share on other sites

  • 0

I tested this on several other laptops and it seems to happen to all of them the same thing... One thing to note, is that, this only seem to happen to wireless network cards. One curiosity though, is that the ones I tested, are all the same: Intel? PRO/Wireless 2200BG

Can't anyone help me out with this? No one understands this WMI thing that could help me out?

I don't have a wireless card so I wouldn't be much help. There are return codes for that method, EnableDHCP. Have you examined them? It returns an uint.

http://msdn2.microsoft.com/en-us/library/aa390378.aspx

Link to comment
Share on other sites

  • 0

Ok, I just found something...

To get the return code, instead of using vb.net, I used vbscript. Created a file with a simple vbs script and tried the same stuff as the vb.net code above.

Anyway, I tried to enable DHCP to the wireless card with the vbscript and it worked, then I tried with my code without any changes, and it also workd, that's when I thought to myself that something was wrong... I decided to retest the not wireless card, and now, that one didn't work. After a few more repeated tests I came to this conclusion:

If the card is connected to anything (without the red X on the connection icon) it works to any of them, enabling DHCP works just fine. But if I try to enable DHCP to any connection not connected, I get the "bug" in the screenshot.

The return code, reported by the vbscript was this: 94 - Path, file, or object not found.

When it worked, the return code was (of course): 0 - Successful completion, no reboot required.

Now, I'm more confused than before... I don't understand the error 94... I have this:

If objNetAdapter.Caption = "[00000012] Intel(R) PRO/Wireless 2200BG Network Connection" Then
		errEnable = objNetAdapter.EnableDHCP()
		Wscript.Echo errEnable
	End If

And it obviously entered the If statement (cause the error code is reported), which means it founds the "object" (I guess?). How come it can't fully enable DHCP?

I think it makes a bit of sense, thinking that DHCP is supposed to find the ips to use in the card and if we are not connected it won't get any ips from anywhere, but it should at least "select" the option to obtain ip address automatically...

Any ideas?

Link to comment
Share on other sites

  • 0

Ok, I just found something...

To get the return code, instead of using vb.net, I used vbscript. Created a file with a simple vbs script and tried the same stuff as the vb.net code above.

Anyway, I tried to enable DHCP to the wireless card with the vbscript and it worked, then I tried with my code without any changes, and it also workd, that's when I thought to myself that something was wrong... I decided to retest the not wireless card, and now, that one didn't work. After a few more repeated tests I came to this conclusion:

If the card is connected to anything (without the red X on the connection icon) it works to any of them, enabling DHCP works just fine. But if I try to enable DHCP to any connection not connected, I get the "bug" in the screenshot.

The return code, reported by the vbscript was this: 94 - Path, file, or object not found.

When it worked, the return code was (of course): 0 - Successful completion, no reboot required.

Now, I'm more confused than before... I don't understand the error 94... I have this:

If objNetAdapter.Caption = "[00000012] Intel(R) PRO/Wireless 2200BG Network Connection" Then
		errEnable = objNetAdapter.EnableDHCP()
		Wscript.Echo errEnable
	End If

And it obviously entered the If statement (cause the error code is reported), which means it founds the "object" (I guess?). How come it can't fully enable DHCP?

I think it makes a bit of sense, thinking that DHCP is supposed to find the ips to use in the card and if we are not connected it won't get any ips from anywhere, but it should at least "select" the option to obtain ip address automatically...

Any ideas?

As to getting the return code, just change the InvokeMethod to take a different set of args. MS did a bang up job of consistent API design there. LOL

// was this vv
//	ManagementBaseObject enableDHCP = mo.InvokeMethod( "EnableDHCP", null, null);
	object ret = mo.InvokeMethod( "EnableDHCP", new object[]{});
// ret can be cast to an uint and the code can be read.

I'll look into the second problem later, unless you figure it out. Just ran out of time tonight. Sorry.

Link to comment
Share on other sites

  • 0

i don't know c# right off but i'm proficient with vbscript at the moment. i wrote a script to query all my nic cards and returns an output that mimics an IPCONFIG /ALL command from a DOS prompt.

initially it enumerated all the virtual adapters, wan miniport and ras async adapters but i used a few options to filter those out just to give me the true nic card.

first the Win32_NetworkAdapterConfiguration has a boolean IPEnabled that you'll want to set to true like this.

strComputer = "." 
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\CIMV2") 
Set colItems = objWMIService.ExecQuery( _
	"SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled=TRUE")

that should return only your LAN nic card.

from there you would then invoke the enable dhcp method but you have to specify which nic to do so. in your example you're using a specific string to test for but that's not always the best method since so many things can go wrong. so from the above code you'd loop through all the nics with only IPEnabled and use that nics deviceID as the index value and assign it so. like this...

For Each objItem In colItems
	intIndex = objItem.Index
	Set objNic = objWMIService.Get("Win32_NetworkAdapter.DeviceID=" & intIndex)
Next

in the environment for which i wrote this there are other devices that were IPEnabled that i did not want since i only wanted a LAN nic or gigabit connection or whatever you want to call it - it's the nic that the cat5 feeds into.

so i used the NetConnectionStatus property for the Win32_NetworkAdapter class that we just created above like this.

For Each objItem In colItems
	intIndex = objItem.Index
	Set objNic = objWMIService.Get("Win32_NetworkAdapter.DeviceID=" & intIndex)

	strNetConnectionStatus = objNic.NetConnectionStatus

	' a status of 2 or 9 means "connected" so we only get the nics that are online.
	If(strNetConnectionStatus=2) OR (strNetConnectionStatus=9)Then  
		   Set objShare = objWMIService.Get("Win32_NetworkAdapterConfiguration.Index='" & intIndex & "'")

	   Set objOutParams = objWMIService.ExecMethod("Win32_NetworkAdapterConfiguration.Index='" & intIndex & "'", "EnableDHCP")

	   Wscript.Echo "Out Parameters: "
	   Wscript.echo "ReturnValue: " & objOutParams.ReturnValue
   End If
Next

i've tried to break it down step-by-step so here goes the whole deal to recap...

on error resume next
strComputer = "." 
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\CIMV2") 
Set colItems = objWMIService.ExecQuery( _
	"SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled=TRUE")

For Each objItem In colItems
	intIndex = objItem.Index
	Set objNic = objWMIService.Get("Win32_NetworkAdapter.DeviceID=" & intIndex)

	strNetConnectionStatus = objNic.NetConnectionStatus

	' a status of 2 or 9 means "connected" so we only get the nics that are online.
	If(strNetConnectionStatus=2) OR (strNetConnectionStatus=9)Then 
		 ' get the nic by index
				 Set objShare = objWMIService.Get("Win32_NetworkAdapterConfiguration.Index='" & intIndex & "'")

			 Set objOutParams = objWMIService.ExecMethod("Win32_NetworkAdapterConfiguration.Index='" & intIndex & "'", "EnableDHCP")

		 Wscript.Echo "Out Parameters: "
		 Wscript.echo "ReturnValue: " & objOutParams.ReturnValue
	End If
Next

btw, in your vbscript snippet there you don't have any type of error handling which is why it didn't work. basically it encountered an error and then stopped. up above i've told it to keep going if it encounters an error.

hope this helps.

Edited by pacifica
Link to comment
Share on other sites

  • 0

That doesn't matter at all. The VBScript I did was just for testing, not fore real live enviornment using... I just wanted to see, if by using VBScript, I could really enable DHCP without having the problem posted in the screenshot in the first post. But it didn't work, the same thing happens.

As I described on my last post, the problem is that the EnableDHCP method won't work the way I want it if the NIC card is not connected to something... If the NIC icon in the Network Connections has a red X, the EnableDHCP method won't work. The IP will be set to 0.0.0.0 and the Subnet Mask to 255.0.0.0. If the NIC is connected, it will work just fine. That's the real issue here.

I appreciate your help, but I don't think your set of VBScripts will help me in anything...

---

Here's what I think I'll do to fix the problem:

1) With the help from WMI, get the SettingID from the NIC card

2) Enable DHCP directly in the registry

It seems to work fine with my tests. But I really wanted to just use WMI.

Link to comment
Share on other sites

  • 0

no more ideas?

If it doesn't work, it doesn't work. You may want to submit a suggestion to Microsoft to change the behavior, or it may be a bug. I'd get on the Microsoft forums or newsgroups and ask about this first, though.

Link to comment
Share on other sites

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.