• 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
https://www.neowin.net/forum/topic/515984-c-enabling-dhcp-on-nic-through-wmi/
Share on other sites

11 answers to this question

Recommended Posts

  • 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...

  • 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?

  • 0
  Nazgulled said:

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

  • 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?

  • 0
  Nazgulled said:

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.

  • 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.DeviceIDmp; 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.DeviceIDmp; 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.Indexamp; 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.DeviceIDmp; 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.Indexamp; 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
  • 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.

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

    • No registered users viewing this page.
  • Posts

    • I was a little disappointed with mine compared to the Lemokey P1, for example. Seemed cheap compared to all aluminum. But I liked the look to go with my Fractal North. Ended up getting a Keychron Q1 HE and a Lemokey L5 HE. Love the L5, which replaced my P1. The definitely aren't light boards.
    • Thunderbird 139.0.2 by Razvan Serea Thunderbird is a free, open-source, cross-platform application for managing email and news feeds. It is a local (rather than a web-based) email application that is powerful yet easy-to-use. Thunderbird is clean and elegant by default, but easily customizable to match your workflow and visual preferences. It is loaded with unique and powerful features. Thunderbird is developed, tested, translated and supported by the folks at Mozilla Corporation and by a group of dedicated volunteers. Thunderbird gives you control and ownership over your email. There are lots of add-ons available for Thunderbird that enable you to extend and customize your email experience. Thunderbird gives you IMAP/POP support, a built-in RSS reader, support for HTML mail, powerful quick search, saved search folders, advanced message filtering, message grouping, labels, return receipts, smart address book LDAP address completion, import tools, and the ability to manage multiple e-mail and newsgroup accounts. Thunderbird 139.0.2 fixes: Security fixes Download: Thunderbird 139.0.2 for Windows (EN/US) | 32-bit | ~70.0 MB (Open Source) Download: Thunderbird 139.0.2 for Linux (EN/US) | 74.7 MB Download: Thunderbird 139.0.2 for Mac OS (EN/US) | 127.0 MB Download: Thunderbird 139.0.2 in other languages View: Thunderbird Website | Screenshot Get alerted to all of our Software updates on Twitter at @NeowinSoftware
    • Thanks Nik and thanks Mind. Nik: Just on the off chance, you don't know where I could get this part at cheaper than normal price do you? I tried I few places but the I can find it at is 70GBP? Just gonna have to suck it up and buy the add-on for my PC. Thank you guys.
    • Underwhelming update. Same as 12,13,14,15. Then M3E ain't showing up until Q3
  • Recent Achievements

    • Week One Done
      elsa777 earned a badge
      Week One Done
    • One Month Later
      elsa777 earned a badge
      One Month Later
    • First Post
      K Dorman earned a badge
      First Post
    • Reacting Well
      rshit earned a badge
      Reacting Well
    • Reacting Well
      Alan- earned a badge
      Reacting Well
  • Popular Contributors

    1. 1
      +primortal
      544
    2. 2
      ATLien_0
      272
    3. 3
      +FloatingFatMan
      207
    4. 4
      +Edouard
      201
    5. 5
      snowy owl
      139
  • Tell a friend

    Love Neowin? Tell a friend!