• 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

    • OneDrive for Mac now lets you sync files to removable drives by Taras Buria If you use OneDrive on Mac and often work with external drives (a common sight among Mac users where internal storage is not upgradeable), Microsoft has some good news for you: the OneDrive client for macOS now supports removable drives, allowing you to sync files to external disks, both non-removable and removable. Microsoft introduced external drive support in OneDrive for Mac at the beginning of 2025. However, the initial rollout was limited to drives that macOS detects as non-removable. The company received plenty of feedback from users regarding this change, and it is now addressing the inability to sync files to removable drives. External drive support in OneDrive works the same way as syncing files to internal storage. If you unplug your drive, say, a portable SSD, OneDrive will stop syncing and notify you with an error message (there is a short delay for drives that sporadically disconnect). To resume sync, reconnect your drive and restart OneDrive. If you want to sync OneDrive to an external drive, your drive should be formatted for APFS (Apple File System) and protected by FileVault (read-only, network, and quarantined drives are not supported). Also, you need macOS version 15.0 or newer and OneDrive version 25.097 or newer. For now, external drive support is only available for insiders, but a wider rollout is coming soon. Finally, Microsoft adds that external drive support does not allow moving drives between devices. Therefore, you must set up OneDrive sync again every time you connect your drive to a new Mac. You can read more about external drive support in OneDrive for Mac in a post on the official Tech Community website. In other OneDrive news, check out our recently published guide, which details how to change OneDrive folder colors for extra personalization.
    • I'm here for it! Bill Pullman & Rick Moranis Returning For New ‘Spaceballs’; Keke Palmer Also Set https://deadline.com/2025/06/spaceballs-2-casts-rick-moranis-bill-pullman-keke-palmer-1236431204/ It's gonna be epic! 
    • Lipstick on a data-hungry pig...
    • I really feel like we need a 3rd good phone OS option to compete with Google and Apple.
    • After 40 years we asked what the fans want...... and are making this movie anyway! 
  • Recent Achievements

    • One Month Later
      POR2GAL4EVER earned a badge
      One Month Later
    • One Year In
      Orpheus13 earned a badge
      One Year In
    • One Month Later
      Orpheus13 earned a badge
      One Month Later
    • Week One Done
      Orpheus13 earned a badge
      Week One Done
    • Week One Done
      serfegyed earned a badge
      Week One Done
  • Popular Contributors

    1. 1
      +primortal
      536
    2. 2
      ATLien_0
      263
    3. 3
      +FloatingFatMan
      206
    4. 4
      +Edouard
      168
    5. 5
      Xenon
      124
  • Tell a friend

    Love Neowin? Tell a friend!