Click here to Skip to main content
15,893,190 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

Now I'm writing this, I've read about 30 pages over internet and found nothing acceptable.

I have written a code using WMI(Win32_NetworkAdapterConfigurationonfiguration) in VB.Net which sets and clears Gateway/DNS for a specific IPEnabled network adapter.
This code works great on Windows XP/2003 Server, but in Vista/Server 2008 it cannot CLEAR the gateway anyway.
I tried to pass a Null array to SetGatways method, but nothing happened
tried to pass a Null array for GatewayCostMetrics, unsuccessful.
I also tried wbemtest.exe to execute the method directly, but that one doesn't help too.

I don't know if this is a bug or not, but every article I read from microsoft support, ended with no result.

Here I will write 2 VBScript code blocks,
first will write a Gateway/DNS to the preferred IPEnabled NIC and second will attempt to clear those.

I appreciate any help on this issue.

Gateway/DNS Set code:
VBScript
strComputer = "."
arrDefaultGateways = Array("192.168.0.1")
arrGatewayCostMetrics = Array(1) ' uint16
arrDNSServers = Array("192.168.0.1")
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colNicConfigs = objWMIService.ExecQuery _
    ("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = True")
For Each objNicConfig In colNicConfigs
    If objNicConfig.IPEnabled Then
        strText = objNicConfig.Description & vbNewLine _
            & objNicConfig.MACAddress & vbNewLine & vbNewLine _
            & "Do you want to change Gateway/DNS of this NIC?"
        strTitle = "Question..."
        intMsg = MsgBox(strText,vbYesNo,strTitle)
        Select Case intMsg
            Case 6 'yes
                intGWReturn = objNicConfig.SetGateways(arrDefaultGateways, _
                    arrGatewayCostMetrics)
                intDNSReturn = objNicConfig.SetDNSServerSearchOrder(arrDNSServers)
                If (intGWReturn + intDNSReturn = 0) Then
                    WScript.Echo "Successful"
                Else
                    WScript.Echo "Gateway Return code= "  & intGWReturn _
                        & vbNewLine & "DNS Return code= " & intDNSReturn
                End If
                Exit For
            Case 7 'no
        End Select
    End If
Next


Gateway/DNS Clear code:
VBScript
strComputer = "."
arrDefaultGateways = Array() 	' < Empty Array
arrGatewayCostMetrics = Array() ' < Empty Array
arrDNSServers = Array() 		' < Empty Array
Set objWMIService = GetObject("winmgmts:" _
	& "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colNicConfigs = objWMIService.ExecQuery _
	("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = True")
For Each objNicConfig In colNicConfigs
	If objNicConfig.IPEnabled Then
		strText = objNicConfig.Description & vbNewLine _
			& objNicConfig.MACAddress & vbNewLine & vbNewLine _
			& "Do you want to change Gateway/DNS of this NIC?"
		strTitle = "Question..."
		intMsg = MsgBox(strText,vbYesNo,strTitle)
		Select Case intMsg
			Case 6 'yes
				intGWReturn = objNicConfig.SetGateways(arrDefaultGateways, _
					arrGatewayCostMetrics)
				intDNSReturn = objNicConfig.SetDNSServerSearchOrder(arrDNSServers)
				If (intGWReturn + intDNSReturn = 0) Then
					WScript.Echo "Successful"
				Else
					WScript.Echo "Gateway Return code= "  & intGWReturn _
						& vbNewLine & "DNS Return code= " & intDNSReturn
				End If
				Exit For
			Case 7 'no
		End Select
	End If
Next
Posted
Updated 29-Jan-17 11:19am

Hi,
I had the same problem in C#. I did the following:
First I enabled DHCP.Then i copy the List of Geatways into an array.
After that I reset the Geatway manually to the last value of the array(Which is allways the Gateway recived from the DHCP server).
As a last step I enable DHCP again.

Here is my Code in C#:

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 ) )
					{
                        //Enable DHCP         
                        ManagementBaseObject newDNS = mo.GetMethodParameters( "SetDNSServerSearchOrder" );
						newDNS[ "DNSServerSearchOrder" ] = null;
						ManagementBaseObject enableDHCP = mo.InvokeMethod( "EnableDHCP", null, null);
						ManagementBaseObject setDNS = mo.InvokeMethod( "SetDNSServerSearchOrder", newDNS, null);
                        //Save all Gateways into an array
                        string[] gateways = (string[])mo["DefaultIPGateway"];
                       
                        ManagementBaseObject newIP = mo.GetMethodParameters("EnableStatic");                 
                        ManagementBaseObject newGate = mo.GetMethodParameters("SetGateways");
                                               
                        //Set last value of the array(always the Gateway recived by DHCP) as the default Gateway
                        newGate["DefaultIPGateway"] = new string[] {gateways[gateways.Length-1]};                   
                        newGate["GatewayCostMetric"] = new int[] { 1 };
                        //Set IP settings back to static
                        ManagementBaseObject setIP = mo.InvokeMethod("EnableStatic", newIP, null);
                        ManagementBaseObject setGateways = mo.InvokeMethod("SetGateways", newGate, null);
                        //Enable DHCP  again
                        newDNS["DNSServerSearchOrder"] = null;
                        ManagementBaseObject enableDHCP2 = mo.InvokeMethod("EnableDHCP", null, null);
                        ManagementBaseObject setDNS2 = mo.InvokeMethod("SetDNSServerSearchOrder", newDNS, null);
					}
				}
			}


Maybe not the most elegant way to do it, but it works
 
Share this answer
 
Based on the other solution, but this will ignore IPv6 and without DNS...

1) Enable DHCP
2) RenewDHCPLease
3) FixGateway()

C#
public static void FixGateway(string networkInterfaceId)
        {
            foreach (ManagementObject adapter in new ManagementClass("Win32_NetworkAdapterConfiguration").GetInstances())
            {
                if (adapter["SettingID"] as string == networkInterfaceId)
                {
                    string[] gateways = (string[])adapter["DefaultIPGateway"];

                    string gateway = string.Empty;

                    foreach (string gw in gateways)
                    {
                        if (IPAddress.Parse(gw).AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                            gateway = gw;
                    }

                    ManagementBaseObject newIP = adapter.GetMethodParameters("EnableStatic");

                    adapter.InvokeMethod("EnableStatic", newIP, null);

                    ManagementBaseObject newGateway = adapter.GetMethodParameters("SetGateways");

                    newGateway["DefaultIPGateway"] = new string[] { gateway };
                    newGateway["GatewayCostMetric"] = new int[] { 1 };
                    
                    adapter.InvokeMethod("SetGateways", newGateway, null);

                    adapter.InvokeMethod("EnableDHCP", null, null);
                }
            }
        }
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900