0

I want to add multiple IP addresses in my Ethernet port. I tried below both way

  1. using Management Class

    public void setIP()
        {
            string myDesc = "Realtek USB GbE Family Controller";
            string gateway = "10.210.255.1";
            string subnetMask = "255.255.255.0";
            string address = "10.210.255.102";
    
            var adapterConfig = new ManagementClass("Win32_NetworkAdapterConfiguration");
            var networkCollection = adapterConfig.GetInstances();
    
            foreach (ManagementObject adapter in networkCollection)
            {
                string description = adapter["Description"] as string;
                if (string.Compare(description,
                    myDesc, StringComparison.InvariantCultureIgnoreCase) == 0)
                {
                    try
                    {
                        // Set DefaultGateway
                        var newGateway = adapter.GetMethodParameters("SetGateways");
                        newGateway["DefaultIPGateway"] = new string[] { gateway };
                        newGateway["GatewayCostMetric"] = new int[] { 1 };
    
                        // Set IPAddress and Subnet Mask
                        var newAddress = adapter.GetMethodParameters("EnableStatic");
                        newAddress["IPAddress"] = new string[] { address };
                        newAddress["SubnetMask"] = new string[] { subnetMask };
    
                        adapter.InvokeMethod("EnableStatic", newAddress, null);
                        adapter.InvokeMethod("SetGateways", newGateway, null);
    
                        Console.WriteLine("Updated to static IP address!");
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Unable to Set IP : " + ex.Message);
                    }
                }
            }
        }
    
  2. Using PowerShellSCript in C#

    private string RunScript()
        {
    
                  string scriptText = "$iplist = \"10.210.255.102\"" + "," + " \"10.210.255.103\"" + "\nforeach ($ip in $iplist)" +"\n{" +" \nNew-NetIPAddress -InterfaceAlias \"Ethernet\" -IPAddress $ip -PrefixLength 24" +"\n}";
    
            // create Powershell runspace
    
            Runspace runspace = RunspaceFactory.CreateRunspace();
    
            // open it
    
            runspace.Open();
    
            // create a pipeline and feed it the script text
    
            Pipeline pipeline = runspace.CreatePipeline();
            pipeline.Commands.AddScript(scriptText);
    
            // add an extra command to transform the script
            // output objects into nicely formatted strings
    
            // remove this line to get the actual objects
            // that the script returns. For example, the script
    
            // "Get-Process" returns a collection
            // of System.Diagnostics.Process instances.
    
            pipeline.Commands.Add("Out-String");
    
            // execute the script
    
            var results = pipeline.Invoke();
    
            // close the runspace
    
            runspace.Close();
    
            // convert the script result into a single string
    
            StringBuilder stringBuilder = new StringBuilder();
            foreach (PSObject obj in results)
            {
                stringBuilder.AppendLine(obj.ToString());
            }
    
            return stringBuilder.ToString();
        }
    

Both are not working, my code working properly it's not going inside catch, but not able to add IP, even I can add IP using running power script file from Windows PowerShell, but the same script is not working inside C#,

all I am trying to add a number of IP address in Single Ethernet card

Note: yes I have Admin rights, I already perform this manually and using PowerShell tool power script. one more thing, every time i have to right-click window PowerShell and run as administrator to run my scrip

VARUN NAYAK
  • 656
  • 5
  • 15
  • 36
  • What is returned by your two calls to `adapter.InvokeMethod()`? You don't check the result. Just because no exception is thrown doesn't mean the invoked method succeeded. – Lance U. Matthews Sep 11 '19 at 20:44
  • Also, your question is essentially "Why does this first snippet execute without errors but not produce the expected result?" _and_ "Why does this second script work when invoked directly from PowerShell but not C#?" That's good that you tried multiple approaches to solve your problem, but asking about two completely different attempts that are each failing in a different way I think makes this question too broad. Unless you're just looking for _any_ way to set static IPs, in which case I'd be surprised if that hasn't been asked before ([similar?](https://stackoverflow.com/q/209779/150605)). – Lance U. Matthews Sep 11 '19 at 21:00
  • @BACON I already tried a solution which you are suggesting, yes ultimately I want to add multiple static IP, but something is wrong, some setting, registry I don't know, thats why I posted multiple ways just to figure out what exactly I am missing – VARUN NAYAK Sep 11 '19 at 21:19

2 Answers2

0

for the Powershell solution, it can be a real pain to get a script working in c#. Usually I prefer using the Powershell class, you can try this approach:

Using Scripts:

var Ps = PowerShell.Create();
//you can create the variable like this:
Ps.AddCommand("Set-Variable").AddParameter("Name", "tsinfo").AddParameter("Value", result);
Ps.Invoke();
//Execute your script
Ps.Commands.Clear();
Ps.AddScript("foreach ($ip in $iplist)" +"\n{" +" \nNew-NetIPAddress -InterfaceAlias \"Ethernet\" -IPAddress $ip -PrefixLength 24" +"\n}");
Ps.Invoke();

Or using Commands:

var iplist = new List<string> { "10.210.255.102", "10.210.255.103"};
foreach(var ip in iplist){
    Ps.Commands.Clear();
    Ps.AddCommand("New-NetIPAddress").AddParameter("InterfaceAlias", "Ethernet").AddParameter("IPAddress", ip).AddParameter("PrefixLength", 24);
    Ps.Invoke();
}

Hope it'll help

vvilin
  • 185
  • 10
  • Same as what My code does, no Error but simply IP not added. I run a solution as an administrator and the above question code is working now !! – VARUN NAYAK Sep 12 '19 at 16:44
0

Problem Solved, Run Exe As a administratoror, Run Visual studio as a Administrator .

I go further and added multiple IP addresses, and Subnet makst in Single Ethernet card

var newAddress = adapter.GetMethodParameters("EnableStatic");
                        newAddress["IPAddress"] = new string[] { address, address1 };
                        newAddress["SubnetMask"] = new string[] { subnetMask,subnetMask };

                        var cal1 = adapter.InvokeMethod("EnableStatic", newAddress, null);
VARUN NAYAK
  • 656
  • 5
  • 15
  • 36
  • The question stated you were already running as an administrator, so I don't understand how this is the solution. Was your code running with an administrator-but-not-elevated security token? Also, had you checked the return values of the `adapter.InvokeMethod()` calls presumably they would have returned [`WBEM_E_ACCESS_DENIED`](https://learn.microsoft.com/windows/win32/wmisdk/wmi-error-constants#WBEM_E_ACCESS_DENIED) or [`ERROR_ACCESS_DENIED`](https://learn.microsoft.com/windows/win32/debug/system-error-codes--0-499-#ERROR_ACCESS_DENIED) to indicate a rights issue. – Lance U. Matthews Sep 12 '19 at 17:24
  • @BACON yes I checked return value it doesn't return any Error, my user has administrator rights but I don't know why its require to start the application as an administrator. – VARUN NAYAK Sep 12 '19 at 19:20