Click here to Skip to main content
15,881,559 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,
I've been trying to write a code to change my IP address, but when I run my code the IP address is the same as before. can anybody help me to understand what's wrong?
thanks.

code:
private void Form1_Load(object sender, EventArgs e)
{
    textBox1.Text = getip();
    setIP("192.168.97.51","255.255.255.0");
    textBox2.Text = getip();
}
public string getip()
{
    IPHostEntry host;
    string localIP = "?";
    host = Dns.GetHostEntry(Dns.GetHostName());
    foreach (IPAddress ip in host.AddressList)
    {
        if (ip.AddressFamily.ToString() == "InterNetwork")
        {
            localIP = ip.ToString();
        }
    }
    return localIP;
}
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"])
        {
            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);
        }
    }
}
Posted
Comments
amirmohamad 20-Sep-12 5:32am    
be nazar moshkeli nadare!!!
shayad aslan nashe IP ro avaz koni
mehdi_k 20-Sep-12 5:37am    
osolan bayad ba in code beshe!
nemifahmam cheshe.

1 solution

This is the right way! but check "ipenabled" criteria of the NIC


newIP[ "IPAddress" ] = IpAddresses.Split( ',' );
C#
newIP[ "IPAddress" ] = IpAddresses.Split( ',' );
newIP[ "SubnetMask" ] = new string[] { SubnetMask };

setIP = mo.InvokeMethod( "EnableStatic", newIP, null);
 
Share this answer
 
v4
Comments
mehdi_k 20-Sep-12 8:20am    
thanks, but no change.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900