Hi Friends,
You have learned to Get IP Address in C#
from the last post. Here you can learn to change IP Address using C#.
Let's start;
Steps
1. Open Visual Studio and Create a New Project -> Windows Form Application with
Name IP Setter.
2. Now add 1 label, 1 textbox and 1 button to the form and design it as shown in the
below image. Give the textbox and the button with names txtIP and btnSetIP. Also
name your form as IP Setter.
3. Now double click on the Set IP button and update the code with the one shown below.
Form1.cs
using System;
using System.Management;
using System.Windows.Forms;
namespace IP_Setter
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public 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);
}
catch (Exception)
{
}
}
}
}
private void btnSetIP_Click(object sender, EventArgs e)
{
string newIP = txtIP.Text;
string subnetMask = "255.255.255.0";
setIP(newIP, subnetMask);
MessageBox.Show("IP Changed Successfully");
}
}
}
4. Now you have to add a reference to System.Management. For doing so, follow
the steps given below;
- Right click on the Project from Solution Explorer and select Add Reference.
- Now select System.Management from the Assemblies tab and press OK. So you have imported this namespace to the project
- Now Right Click on the code that shows error related to Management and select Resolve -> Using System.Management( See the screenshot.)
5. So you have done your project, now Run it and change your IP using C#.
ENJOY.
In case of any queries / errors, please drop a comment.
See Also
This Code is running but cant change my PC IP. please suggest what i should i do
ReplyDeletethe program runs correctly without errors and an "IP Changed Successfully" message appears ,but the IP stays the same and doesn't change...what is the problem?
ReplyDeleteHi, thanks.
ReplyDeleteIf we change IP, will there be any impact on Internet on that PC?
After changing IP, internet should work as it is, right ?
this code cannot change but it runs without errors
ReplyDelete