Changing IP Address

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Mudassir
    New Member
    • May 2012
    • 85

    Changing IP Address

    Dear all

    i am developing an application which will change the ip address of the server. the Ip is configured manually (i.e static ip configuration). i have written the following code to do so
    Code:
    private void setIP(string ip_address, string subnet_mask)
            {
               ManagementClass objMC = new ManagementClass("Win32_NetworkAdapterConfiguration");
                ManagementObjectCollection objMOC = objMC.GetInstances();
    
                foreach (ManagementObject objMO in objMOC)
                {
                    if ((bool)objMO["IPEnabled"])
                    {
                        try
                        {
                            ManagementBaseObject setIP;
                            ManagementBaseObject newIP =
                                objMO.GetMethodParameters("EnableStatic");
    
                            newIP["IPAddress"] = new string[] { ip_address };
                            newIP["SubnetMask"] = new string[] { subnet_mask };
    
                            setIP = objMO.InvokeMethod("EnableStatic", newIP, null);
    WriteLog("Ip changed, new IP assigned is "+ip_address + System.Environment.NewLine + "=================" + System.Environment.NewLine);
                        }
                        catch (Exception ex)
                        {
                            WriteLog("Error Occured.. " + ex.Message.ToString() + System.Environment.NewLine + "=================" + System.Environment.NewLine);
                        }
    
    
                    }
                }
            }
    the code is not giving any error and when i check the log file created, it shows the message that the new ip is assigned. but when i check in the Local area connection status, it shows the same old ip..

    any help will be greatly appreciated..

    Regards:
  • Luuk
    Recognized Expert Top Contributor
    • Mar 2012
    • 1043

    #2
    see: http://msdn.microsoft.com/en-us/libr...spx#properties

    IPAddressData
    type: string array
    Access type: Read-only

    A possible solution is to use NETSH
    Code:
    netsh int ip set address "local area connection" static 192.168.0.101 255.255.255.0 192.168.0.254 1

    Comment

    • Mudassir
      New Member
      • May 2012
      • 85

      #3
      Thnx Luuk,
      can you plz explain it in some detail???

      Comment

      • Luuk
        Recognized Expert Top Contributor
        • Mar 2012
        • 1043

        #4
        The first part is a reference to the 'manual', where is says that 'IPAddressData' is a Read-Only field.
        This means that you cannot change is through that interface.

        for the second part, the 'NETSH'-thing, I have to forward you to: https://social.msdn.microsoft.com/Fo...=csharpgeneral

        Comment

        • Mudassir
          New Member
          • May 2012
          • 85

          #5
          Dear Luuk.
          i used following code with netsh command
          Code:
          string command = "netsh int ip set address= \"local area connection\" static " + ip_address + " 255.255.255.0 192.168.0.1";
                      ProcessStartInfo procStartInfo = new ProcessStartInfo()
                      {
                          RedirectStandardError = true,
                          RedirectStandardOutput = true,
                          UseShellExecute = false,
                          CreateNoWindow = true,
                          FileName = "runas.exe",
                          Arguments = "/user:Administrator \"cmd /K " + command + "\""
                      };
          
                      using (Process proc = new Process())
                      {
                          proc.StartInfo = procStartInfo;
                          proc.Start();
          
                          string output = proc.StandardOutput.ReadToEnd();
          
                          if (string.IsNullOrEmpty(output))
                              output = proc.StandardError.ReadToEnd();
          
                          
                      }
          but it is not changing the ip address at all.. and when i run the command prompt as administrator from the start menu and type the same command, it changes the ip address. is there any way to run the command prompt as administrator from c# code ?

          Comment

          • Luuk
            Recognized Expert Top Contributor
            • Mar 2012
            • 1043

            #6
            I took the opportunity to Google for the answer using:
            'c# run code elevated privileges'

            The first result of this search links to:


            The code give there, seems to do what you want it to do!

            Comment

            • Mudassir
              New Member
              • May 2012
              • 85

              #7
              thnx Luuk for your reply but i solved the problem by making some changes in my code..

              Regards:

              Comment

              • Joseph Martell
                Recognized Expert New Member
                • Jan 2010
                • 198

                #8
                Mudassir,

                I have been working on a similar program for quite a while now. I went down the Management Object route at first, but ran into the exact problem you stated above.

                I did not want to use shell commands for various reasons. The next most common answer I saw online was to modify the IP address directly the registry. This has another set of problems, the biggest being that the IP address will not update until the network connection is disabled and re-enabled (or the network cable is unplugged and plugged back in).

                Eventually I found IP Helper API. It is a C/C++ style API included in Windows OS natively. It has functions for modifying IP addresses and network settings. Getting it to work in C# is quite a task as it requires working with p/invoke and marshaling objects into and out of unmanaged memory. Rather tedious and a bit of a chore.

                You can check it out here:


                Calling netsh will be functional with far less code, but if you ever decide to revisit this the IP Helper API is the only way I have found so far to gain access to the functionality you are after.

                Also, please post your modified code. I would like to see how you worked around the elevated permissions problem.

                Comment

                • arifemre61
                  New Member
                  • Dec 2015
                  • 1

                  #9
                  Hi

                  Hi Mudassir
                  How did you solve the problem in your code? Could you give detail what did you do exactyl ?
                  Thank you.

                  Originally posted by Mudassir
                  thnx Luuk for your reply but i solved the problem by making some changes in my code..

                  Regards:

                  Comment

                  • Mudassir
                    New Member
                    • May 2012
                    • 85

                    #10
                    arifemre61:
                    here is my code which i used to switch ip address.
                    Code:
                    private string changeIP(string _currentIp)
                            {
                                DataSet ds = GetDataSetForGridView("select IP from tbl_IPs where IP <>'" + _currentIp + "' and Used=0 order by NEWID();");
                                if (ds.Tables[0].Rows.Count > 0)
                                {
                                    string newIP = ds.Tables[0].Rows[0]["IP"].ToString();
                                    setIP(false, newIP, "your_sub_net_mask", "your_default_gateway");
                                    string hostNameA = Dns.GetHostName();
                                    return Dns.GetHostByName(hostNameA).AddressList[0].ToString();
                                }
                                else return "all ips used";
                            }
                            private void setIP(bool old, string _iP,string _subnetMask, string _defaultGateway)
                            {
                    
                                string cmd = "";
                                if (old == false)
                                    cmd = "interface ip set address name = \"Local Area Connection\" static " + _iP + " " + __subnetMask +" " + _defaultGateway;
                                else
                                    cmd = "interface ip set address name = \"Local Area Connection\" static 192.132.122.12 "  + __subnetMask +" " + _defaultGateway;
                                Process p = new Process();
                                ProcessStartInfo psi = new ProcessStartInfo("netsh", cmd);
                                p.StartInfo = psi;
                                p.Start();
                                System.Threading.Thread.Sleep(20000);
                            }
                    the netsh command takes 3 parameters which include ip address, gateway and dns.

                    Comment

                    • kamran7679
                      New Member
                      • Jan 2017
                      • 1

                      #11
                      Kamran

                      Checkout the following application

                      Comment

                      Working...