• 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'm just commenting because of this madness. you simply asked "what crowd" which i too am genuinely curious about, only to receive a response in the form of a link that directs to an analysis of the audited financial statements with the accompanying notes. then you say that the guy who wrote it is stupid, which whatever, that's not an argument being discussed atm, only to receive a response from Arceles saying "i don't deal with people whose first response is an ad homenim". jesus. this is like making a claim, and then saying "i don't deal with people who speak in a certain way or swear so i'm not gonna answer you hah!" (said in a nasaly voice, not trying to depict you Arceles). then focus on the argument instead of the explanation begins... "so what don't you like about the guy (lunduke)" followed by "he just likes to insult people" and the explanation for the "crowd" being referred to was never even established. so a request for an explanation about the crowd turned into an argument about "why do you think lunduke is an idiot". wowza.
    • Sony lays off 30% of staff from Days Gone developer Bend Studio by Pulasthi Ariyasinghe Another wave of layoffs has hit the game developer space, and this time, it's a first-party Sony studio that's been affected. Following a report by Bloomberg's Jason Schreier, Bend Studio has confirmed that it is letting go of "incredibly talented teammates" as it begins work on a new game project. "Today, we said goodbye to some incredibly talented teammates as we transition to our next project," said Bend Studio in a social media post today. "We're deeply thankful for their contributions as they've shaped who we are, and their impact will always be part of our story." Bend Studio is most well-known for its 2019-released open-world zombie adventure Days Gone, which even received a remaster just a few months ago. Prior to that, the studio had been responsible for the classic Syphon Filter series while also developing several PlayStation Portable and Vita games like Resistance: Retribution and Uncharted: Golden Abyss, respectively. "This is a difficult moment for our team, but we hold immense respect for everyone who got us here," the company added. "As we move forward, we remain committed to building the future of Bend Studio with creativity, passion, and innovation in the titles we craft." While Sony did not detail just how many staff have been affected by this latest decision, Jason Schreier revealed that 30% of the studio is being laid off. This amounts to around 40 people, according to the reporter. Earlier this year, Sony canceled two live service games that were in development at Bend Studio and Bluepoint Games. It was never revealed what this mystery game was supposed to be. "Bend and Bluepoint are highly accomplished teams who are valued members of the PlayStation Studios family," Sony said at the time. It's unclear if Bluepoint, which had been developing a God of War live service experience, will soon be hit by its own wave of layoffs too.
    • KataLib 4.5.3.0 by Razvan Serea KataLib is more than just a music player — it's a complete audio suite designed for music lovers and creators alike. It combines a powerful audio player, a flexible metadata editor, a capable audio converter, and a music library manager into one streamlined application. Core Features: Audio Player Enjoy seamless playback of virtually any audio format or even streaming video files. DJ Mode lets you mix tracks with manual or automatic crossfades. You can also load and save WinAmp-style playlists for quick access to your favorite sets. Audio Converter Convert between a wide range of audio formats effortlessly. Trim or normalize your output automatically, and even extract audio from streaming video sources. Ideal for preparing files for different devices or platforms. Metadata Editor View and edit ID3v2 tags and other metadata. Batch edit multiple files at once, and fetch missing information directly from the MusicBrainz database. You can also apply or update album art with ease. Music Library Manager Organize your entire audio collection, search across tracks instantly, and download cover images from the internet — or use your own custom artwork. KataLib makes it easy to keep your library tidy and enriched with useful info. Supported Formats: KataLib supports a wide range of both lossy and lossless audio formats: Input: OPUS, AAC, FLAC, M4A, MP3, MP4, MPC, APE, AIF, MKV, AVI, MOV, FLV, WEBM, Ogg Vorbis, WAV, WAVPack, WMA Output: OPUS, FLAC, M4A, MP3, Ogg Vorbis, WAV Under the hood, KataLib uses the trusted FFmpeg engine for audio conversion and media playback, ensuring compatibility with virtually all mainstream media formats. Download: KataLib 4.5.3.0 | 64.5 MB (Open Source) Links: KataLib Home Page | Github | Screenshot Get alerted to all of our Software updates on Twitter at @NeowinSoftware
    • I had this issue and it is a nova android conflict issue. Initially the only way to fix it was clicking the screen off and then back on. Figured out it was because of a task I set up in tasker to load certain apps when I connect to my car, so fixed it by adding a 'go home' task after the app loaded and rarely have the issue now
    • I wish one of the windows updates hadn't broken glass. Is there a workaround for that I'm not aware of?
  • Recent Achievements

    • Reacting Well
      rshit earned a badge
      Reacting Well
    • Reacting Well
      Alan- earned a badge
      Reacting Well
    • Week One Done
      IAMFLUXX earned a badge
      Week One Done
    • One Month Later
      Æhund earned a badge
      One Month Later
    • One Month Later
      CoolRaoul earned a badge
      One Month Later
  • Popular Contributors

    1. 1
      +primortal
      542
    2. 2
      ATLien_0
      269
    3. 3
      +FloatingFatMan
      210
    4. 4
      +Edouard
      203
    5. 5
      snowy owl
      140
  • Tell a friend

    Love Neowin? Tell a friend!