473,395 Members | 2,783 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

Changing IP Address

85 64KB
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
Expand|Select|Wrap|Line Numbers
  1. private void setIP(string ip_address, string subnet_mask)
  2.         {
  3.            ManagementClass objMC = new ManagementClass("Win32_NetworkAdapterConfiguration");
  4.             ManagementObjectCollection objMOC = objMC.GetInstances();
  5.  
  6.             foreach (ManagementObject objMO in objMOC)
  7.             {
  8.                 if ((bool)objMO["IPEnabled"])
  9.                 {
  10.                     try
  11.                     {
  12.                         ManagementBaseObject setIP;
  13.                         ManagementBaseObject newIP =
  14.                             objMO.GetMethodParameters("EnableStatic");
  15.  
  16.                         newIP["IPAddress"] = new string[] { ip_address };
  17.                         newIP["SubnetMask"] = new string[] { subnet_mask };
  18.  
  19.                         setIP = objMO.InvokeMethod("EnableStatic", newIP, null);
  20. WriteLog("Ip changed, new IP assigned is "+ip_address + System.Environment.NewLine + "=================" + System.Environment.NewLine);
  21.                     }
  22.                     catch (Exception ex)
  23.                     {
  24.                         WriteLog("Error Occured.. " + ex.Message.ToString() + System.Environment.NewLine + "=================" + System.Environment.NewLine);
  25.                     }
  26.  
  27.  
  28.                 }
  29.             }
  30.         }
  31.  
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:
Dec 30 '14 #1
10 16054
Luuk
1,047 Expert 1GB
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
Expand|Select|Wrap|Line Numbers
  1. netsh int ip set address "local area connection" static 192.168.0.101 255.255.255.0 192.168.0.254 1 
Dec 30 '14 #2
Mudassir
85 64KB
Thnx Luuk,
can you plz explain it in some detail???
Dec 30 '14 #3
Luuk
1,047 Expert 1GB
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
Dec 30 '14 #4
Mudassir
85 64KB
Dear Luuk.
i used following code with netsh command
Expand|Select|Wrap|Line Numbers
  1. string command = "netsh int ip set address= \"local area connection\" static " + ip_address + " 255.255.255.0 192.168.0.1";
  2.             ProcessStartInfo procStartInfo = new ProcessStartInfo()
  3.             {
  4.                 RedirectStandardError = true,
  5.                 RedirectStandardOutput = true,
  6.                 UseShellExecute = false,
  7.                 CreateNoWindow = true,
  8.                 FileName = "runas.exe",
  9.                 Arguments = "/user:Administrator \"cmd /K " + command + "\""
  10.             };
  11.  
  12.             using (Process proc = new Process())
  13.             {
  14.                 proc.StartInfo = procStartInfo;
  15.                 proc.Start();
  16.  
  17.                 string output = proc.StandardOutput.ReadToEnd();
  18.  
  19.                 if (string.IsNullOrEmpty(output))
  20.                     output = proc.StandardError.ReadToEnd();
  21.  
  22.  
  23.             }
  24.  
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 ?
Dec 31 '14 #5
Luuk
1,047 Expert 1GB
I took the opportunity to Google for the answer using:
'c# run code elevated privileges'

The first result of this search links to:
http://www.codeproject.com/Articles/...Demand-using-C

The code give there, seems to do what you want it to do!
Dec 31 '14 #6
Mudassir
85 64KB
thnx Luuk for your reply but i solved the problem by making some changes in my code..

Regards:
Jan 1 '15 #7
Joseph Martell
198 Expert 128KB
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:
http://msdn.microsoft.com/en-us/libr...=vs.85%29.aspx

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.
Jan 16 '15 #8
Hi Mudassir
How did you solve the problem in your code? Could you give detail what did you do exactyl ?
Thank you.

@Mudassir
Dec 24 '15 #9
Mudassir
85 64KB
arifemre61:
here is my code which i used to switch ip address.
Expand|Select|Wrap|Line Numbers
  1. private string changeIP(string _currentIp)
  2.         {
  3.             DataSet ds = GetDataSetForGridView("select IP from tbl_IPs where IP <>'" + _currentIp + "' and Used=0 order by NEWID();");
  4.             if (ds.Tables[0].Rows.Count > 0)
  5.             {
  6.                 string newIP = ds.Tables[0].Rows[0]["IP"].ToString();
  7.                 setIP(false, newIP, "your_sub_net_mask", "your_default_gateway");
  8.                 string hostNameA = Dns.GetHostName();
  9.                 return Dns.GetHostByName(hostNameA).AddressList[0].ToString();
  10.             }
  11.             else return "all ips used";
  12.         }
  13.         private void setIP(bool old, string _iP,string _subnetMask, string _defaultGateway)
  14.         {
  15.  
  16.             string cmd = "";
  17.             if (old == false)
  18.                 cmd = "interface ip set address name = \"Local Area Connection\" static " + _iP + " " + __subnetMask +" " + _defaultGateway;
  19.             else
  20.                 cmd = "interface ip set address name = \"Local Area Connection\" static 192.132.122.12 "  + __subnetMask +" " + _defaultGateway;
  21.             Process p = new Process();
  22.             ProcessStartInfo psi = new ProcessStartInfo("netsh", cmd);
  23.             p.StartInfo = psi;
  24.             p.Start();
  25.             System.Threading.Thread.Sleep(20000);
  26.         }
  27.  
the netsh command takes 3 parameters which include ip address, gateway and dns.
Dec 26 '15 #10
Checkout the following application

https://github.com/kamran7679/ConfigureIP.git
Jan 25 '17 #11

Sign in to post your reply or Sign up for a free account.

Similar topics

1
by: Stefano | last post by:
Hi all, i need to change an URL in location bar without change original address: for example: user asks www.google.it and over location bar appears www.myaddress.it. Is it possibile? thanks!...
3
by: Geoff Soper | last post by:
I'm trying to dynamically change the cursor of a couple of maps over an image. Basically the image is in an online photo system where there is a rotate mode. In this mode clicking on the left or...
8
by: YAN | last post by:
Hi, I want to get the mac address from a machine, which i have the IP address of that machine, how can i do that? I know how to get the mac address of the local machine from the following code: ...
1
by: hazly | last post by:
I don't know much about MS SQL-Server. I'm having SQL server 2000 and going to change IP address of the server. What need to be done?
3
by: Bernd Giegerich | last post by:
Hi, we had a strange problem with DB2 8.2 Enterprise Edition on Windows 2003 (Standard) Server. We installed DB2 8.2 (8.1.7) directly on a naked W2K3 system (no migration, no update -> no...
3
by: glikoz | last post by:
How to I change address bar wihout going another page. Thanks
12
by: howachen | last post by:
header("Location: http://www.example.com/"); i don't want the browser to show http://www.example.com any method? thanks.
3
by: Newish | last post by:
Hi Regarding DLL base address: 1) What does it mean? 2) Should it ever be changed? 3) What are the rules to change it?
10
by: 7stud | last post by:
Hi, I'm experimenting with a basic socket program(from a book), and both the client and server programs are on my computer. In both programs, I call socket.gethostname(), but I discovered that...
1
by: rufusking | last post by:
My requirement is to change the IP Address of local system programatically using .net. IP Address should change to 10.1.2.100, subnet mask = 255.255.255.0, default gateway=10.1.2.1 I have...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.