• 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

    • LG gram Book 15U50T: Is this lightweight laptop the right upgrade for you? by Paul Hill If you’re in the UK looking for a new mid-range laptop that won’t feel underpowered, check out the LG gram Book 15U50T now because it’s at its all-time lowest price on Amazon UK thanks to a 14% discount from its £699.99 RRP. You can get it now for just £599.99 (Buying link at the end). At this price, the laptop definitely makes this mid-range option much more appealing, it’s also pretty new having only come out in January 2025, so you’re definitely getting more value for your money. The delivery is free and will take a few days to arrive unless you take advantage of a Prime member trial and get it next-day in time for Father’s Day. LG gram Book 15U50T: Key features and who it's for The LG gram Book 15U50T features a 15.6-inch Full-HD (1920x1080) anti-glare IPS display, making it ideal for use in well-lit areas as you won’t see yourself staring back. It’s powered by an Intel Core i5 processor (1334U), 16GB of RAM, and has a very fast 512GB NVMe Gen4 SSD. In my opinion, the storage might be a bit tight for some users; however, the device comes with two M.2 slots if you want to upgrade the storage. The LG gram Book 15U50T is ideal for students or professionals who need a device to carry with them out and about. It has an ultra-lightweight design and weighs just 1.65kg - that’s not too far off a similarly sized MacBook Air, but for a fraction of the cost. In terms of ports, there is an HDMI port, two USB-A ports, and two USB-C ports. There's also a 3.5mm headphone jack if you need to plug in headphones. Other noteworthy details about this laptop include that it's running Windows 11 Home with Copilot integration, it has a HD webcam with a privacy shutter, it uses Dolby Atmos audio for immersive sound, and it has a unique feature called gram Link for multi-device (including Android and iOS) connectivity. Should you buy it? If you are a student or a professional that won’t be doing heavy gaming, or using other super intensive applications, this laptop is a solid pick. It’s lightweight - so easy to carry around, it has an anti-reflective screen - so good in well-lit environments; and it features upgradeable storage slots if 512GB is not enough space. On the downside, this laptop has a mid-range processor that could limit your ability to use high-end professional tools. Another thing I’m not really a fan of here is how opaque LG has been with the battery life. As a portable laptop, you’re obviously going to want to take it on the go where you don’t have a charger handy, but all LG says about the battery is that it has a capacity of 51Wh. According to some online sources, variants of this laptop manage about 7 to 10 hours, so if you need a super long battery life, you might be better off with something like a MacBook Air. So should you buy it? If you’re not going to be doing anything super intensive, but can’t stand underpowered and slow budget laptops then this could be the ideal laptop for you. The £100 discount makes it even more appealing! LG gram Book 15U50T: £599.99 (Amazon UK) / RRP £699.99 This Amazon deal is U.K. specific, and not available in other regions unless specified. If you don't like it or want to look at more options, check out the Amazon UK deals page here. Get Prime, Prime Video, Music Unlimited, Audible or Kindle Unlimited, free for the first 30 days As an Amazon Associate we earn from qualifying purchases.
    • Totally different vehicles. Uber has partnered with Waymo for level 5 autonomous vehicles. Waymo has completed 10 million trips and to date, there have been 696 accidents in 4 years and of those 16 of them appear to have been due to an error by the car. In total airbags have only been deployed 38 times. The technology should always be under review and continued to be improved on, but this is a totally different animal to Tesla FSD PS. no I don't work for them etc. I am an analyst for a market intelligence firm and we have a lot of interest from clients looking at the connected car space for advertising etc. so I have studied them
    • But it's not full self driving it's level 2 autonomy. Audi, BMW and Mercedes all have level 3 and make far less noise about it
    • Edge for Business gets secure password deployment for organizations by Paul Hill Microsoft Edge for Business now offers organizations secure password deployments as a generally available feature, the Redmond giant said. Instead of users sharing passwords on sticky notes or via email to access certain websites or tools, admins can deploy encrypted shared passwords to specific users within their organization. When a user receives a password, it is stored in their Edge password manager and can be used to log into websites seamlessly using autofill. Microsoft has made this enterprise-grade solution available to customers at no additional cost. How it works and the user experience Administrators have to manage the feature via the Microsoft Edge management service within the Microsoft 365 admin center. From there, they can add, update, and revoke credentials for specific user groups through configuration policies. Once an admin has set it up and shared passwords with users, the users will see the passwords in their Edge password manager and can be used with autofill on corresponding websites. The passwords are tied to work profiles in Edge on managed Windows devices to limit their misuse. Further boosting security, the shared passwords cannot actually be viewed, edited, or deleted (unless the website allows), or exported from the password manager. This is a good addition for security because if an unauthorized user gains physical access to the computer, they cannot learn what the password is. Administrators reading this do need to be aware of an important caveat related to developer tools. A motivated user who wants to reveal the passwords can do so by digging into the developer tools, for this reason, you should consider restricting access to the developer tools by configuring the DeveloperToolsAvailability policy. The underlying security and encryption Microsoft’s new secure passwords feature has been built using the Information Protection SDK. The passwords are encrypted and the encryption is tied to Entra identities which lets organizations enforce them without manual key management. The decryption of the passwords takes place at runtime using the same SDK, validating the user’s identity. Availability and getting started Secure password deployment is available through the Edge management service in the Microsoft 365 admin center. Once in the admin center, you should choose an existing configuration policy or create a new one. Inside the policy, go to the Customization Settings tab and then to the Secure password deployment page. To use this feature you must have a Microsoft 365 Business Premium, E3, or E5 subscription. The feature also requires the Edge admin or Global admin role. Source: Microsoft
    • Is it though?  I built a new rig a few months ago and it was literally impossible to get one without RGB, but within 10 minutes of setting it up, I turned all that crap off.  It was REALLY distracting, and who needs additional heat INSIDE a PC? It's popular on YouTube for sure, it's neat looking and whatnot, but it's about as practical as a coffee cup with a hole in it. As for the price, a non-enthusiast would just see something priced way above what they can get from a retailer brand new...
  • Recent Achievements

    • Week One Done
      somar86 earned a badge
      Week One Done
    • One Month Later
      somar86 earned a badge
      One Month Later
    • Apprentice
      Adrian Williams went up a rank
      Apprentice
    • Reacting Well
      BashOrgRu earned a badge
      Reacting Well
    • Collaborator
      CHUNWEI earned a badge
      Collaborator
  • Popular Contributors

    1. 1
      +primortal
      505
    2. 2
      ATLien_0
      260
    3. 3
      +Edouard
      188
    4. 4
      +FloatingFatMan
      175
    5. 5
      snowy owl
      132
  • Tell a friend

    Love Neowin? Tell a friend!