ChangeIP.Source.SetIpAddress.setAddress C# (CSharp) Method

setAddress() public method

public setAddress ( string IPAddress, string SubnetMask, string Gateway ) : void
IPAddress string
SubnetMask string
Gateway string
return void
        public void setAddress(string IPAddress, string SubnetMask, string Gateway)
        {
            ManagementClass objMC = new ManagementClass("Win32_NetworkAdapterConfiguration");
            ManagementObjectCollection objMOC = objMC.GetInstances();

            foreach (ManagementObject objMO in objMOC)
            {
                if (!(bool)objMO["IPEnabled"])
                    continue;
                try
                {
                    ManagementBaseObject objSetIP = null;
                    ManagementBaseObject objNewIP = null;
                    ManagementBaseObject objNewGate = null;

                    objNewIP = objMO.GetMethodParameters("EnableStatic");
                    objNewGate = objMO.GetMethodParameters("SetGateways");

                    objNewIP["IPAddress"] = new string[] { IPAddress };
                    objNewIP["SubnetMask"] = new string[] { SubnetMask };

                    objNewGate["DefaultIPGateway"] = new string[] { Gateway };
                    objNewGate["GatewayCostMetric"] = new int[] { 1 };

                    objSetIP = objMO.InvokeMethod("EnableStatic", objNewIP, null);
                    objSetIP = objMO.InvokeMethod("SetGateways", objNewGate, null);

                    Console.WriteLine("Updated IPAddress, SubnetMask and Default Gateway!");
                    //MessageBox.Show("IPChanged");
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Unable to Set IP : " + ex.Message);
                    //MessageBox.Show("IPnotchanged");
                }
            }
        }

Usage Example

Example #1
0
 private bool ChangeAddress()
 {
     SetIpAddress setIp = new SetIpAddress();
     if ((isInputIpOk(this.ipAddress, rexType.ipAddr)) && (isInputIpOk(this.subnetMask, rexType.ipAddr))
         && (isInputIpOk(this.gatewayAddress, rexType.ipAddr)))
     {
         setIp.setAddress(this.ipAddress, this.subnetMask, this.gatewayAddress);
         return true;
     }
     else
         return false;
 }