C#改IP

这篇博客介绍了如何在C#中利用WMI(Windows Management Instrumentation)或者替代方法来更改系统的IP地址。通过示例代码展示了如何从textbox获取输入的IP,并进行设置,同时讨论了可能遇到的问题和解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Management;
using System.Runtime.InteropServices;

namespace WindowsApplication2
{
    
/**//// <summary>
    
/// Form1 的摘要说明。
    
/// </summary>

    public class Form1 : System.Windows.Forms.Form
    
{
        
private System.Windows.Forms.TextBox textBox1;
        
private System.Windows.Forms.Button button1;
        
/**//// <summary>
        
/// 必需的设计器变量。
        
/// </summary>

        private System.ComponentModel.Container components = null;

        [DllImport(
"kernel32.dll",EntryPoint="SetComputerNameEx")] 
        
public static extern int apiSetComputerNameEx(int iType,string lpComputerName); //这个函数用来改计算机名

        
public Form1()
        
{
            
//
            
// Windows 窗体设计器支持所必需的
            
//
            InitializeComponent();

            
//
            
// TODO: 在 InitializeComponent 调用后添加任何构造函数代码
            
//
        }


        
/**//// <summary>
        
/// 清理所有正在使用的资源。
        
/// </summary>

        protected override void Dispose( bool disposing )
        
{
            
if( disposing )
            
{
                
if (components != null
                
{
                    components.Dispose();
                }

            }

            
base.Dispose( disposing );
        }


        
/**//// <summary>
        
/// 设计器支持所需的方法 - 不要使用代码编辑器修改
        
/// 此方法的内容。
        
/// </summary>

        private void InitializeComponent()
        
{
            
this.textBox1 = new System.Windows.Forms.TextBox();
            
this.button1 = new System.Windows.Forms.Button();
            
this.SuspendLayout();
            
// 
            
// textBox1
            
// 
            this.textBox1.Location = new System.Drawing.Point(816);
            
this.textBox1.Name = "textBox1";
            
this.textBox1.TabIndex = 0;
            
this.textBox1.Text = "xxx";
            
// 
            
// button1
            
// 
            this.button1.Location = new System.Drawing.Point(1648);
            
this.button1.Name = "button1";
            
this.button1.TabIndex = 1;
            
this.button1.Text = "改IP";
            
this.button1.Click += new System.EventHandler(this.button1_Click);
            
// 
            
// Form1
            
// 
            this.AcceptButton = this.button1;
            
this.AutoScaleBaseSize = new System.Drawing.Size(614);
            
this.ClientSize = new System.Drawing.Size(12085);
            
this.Controls.Add(this.button1);
            
this.Controls.Add(this.textBox1);
            
this.Name = "Form1";
            
this.Text = "Form1";
            
this.ResumeLayout(false);

        }


        
/**//// <summary>
        
/// 应用程序的主入口点。
        
/// </summary>

        [STAThread]
        
static void Main() 
        
{
            Application.Run(
new Form1());
        }


        
private void button1_Click(object sender, System.EventArgs e)
        
{
            
this.chktb();
        }

        
        
//这个函数主要是用来检查textbox里输入的内容.
        public void chktb()
        
{
            
string str=textBox1.Text;//计算机名
            string strip="";//IP的最后一位
            try
            
{
                
int a=int.Parse(str);
                strip
=str;
                
if(a>5811)
                
{
                    MessageBox.Show(
"输入的格式不对,请重新输入");
                    textBox1.Text
="";
                    
return;
                }

                
if(a<10)
                
{
                    str
="00"+a.ToString();
                }

                
else if(a<100)
                
{
                    str
="0"+a.ToString();
                }

                str
="XX"+str;            
            }

            
catch
            
{
                
switch(str)
                
{
                    
case "北京大学A":
                        str
="北京大学A";
                        strip
="166";
                        
break;
                    
case "北京大学B":
                        str
="北京大学B";
                        strip
="167";
                        
break;
                    
case "清华大学A":
                        str
="清华大学A";
                        strip
="174";
                        
break;
                    
case "清华大学B":
                        str
="清华大学B";
                        strip
="175";
                        
break;
                    
case "复旦大学A":
                        str
="复旦大学A";
                        strip
="168";
                        
break;
                    
case "复旦大学B":
                        str
="复旦大学B";
                        strip
="169";
                        
break;
                    
case "浙江大学A":
                        str
="浙江大学A";
                        strip
="176";
                        
break;
                    
case "浙江大学B":
                        str
="浙江大学B";
                        strip
="177";
                        
break;
                    
case "上海交大A":
                        str
="上海交大A";
                        strip
="180";
                        
break;
                    
case "上海交大B":
                        str
="上海交大B";
                        strip
="181";
                        
break;
                    
default:
                        MessageBox.Show(
"请输入正确的名字");
                        textBox1.Text
="";
                        
return;
                }

            }

            
//改计算机名,上面调用了一个winapi:setcomputernameEx
            apiSetComputerNameEx(5,str);
            
this.changenet(strip);
        }


        
//这个函数读取textbox里的内容,然后通过里面的内容来更改计算机的IP,网关,dns,及计算机名
        public void changenet(string strip)
        
{
            ManagementBaseObject ib
=null;
            ManagementClass mc 
= new ManagementClass("Win32_NetworkAdapterConfiguration");
            ManagementObjectCollection qc 
= mc.GetInstances();
            
foreach( ManagementObject obj in qc)
            
{
                
if(!(bool)obj["IPEnabled"])//如果网卡没有激活的话就跳过
                    continue;
                
if(int.Parse(((string)obj["Caption"]).Substring(1,8))>100)//这里主要是为了区别物理网卡和拔号连接
                    continue;
                
//这里改IP
                ib=obj.GetMethodParameters("EnableStatic");
                
if(int.Parse(strip)>200)//当计算机的名字大于200号的时候,自动将IP的第三位改成1;
                {
                    
string[] ipstrs={"192.168.1."+strip.Substring(1,2)};
                    ib[
"IPAddress"]=new string[]{"192.168.1."+strip.Substring(1,2)};
                    ib[
"SubnetMask"]=new string[]{"255.255.248.0"};
                }

                
else
                
{
                    ib[
"IPAddress"]=new string[]{"192.168.0."+strip};
                    ib[
"SubnetMask"]=new string[]{"255.255.248.0"};
                }

                obj.InvokeMethod(
"EnableStatic",ib,null);
                
//改网关
                ib=obj.GetMethodParameters("SetGateways");
                ib[
"DefaultIPGateway"]=new string[]{"192.168.0.1"};
                obj.InvokeMethod(
"SetGateways",ib,null);
                
//改DNS
                ib=obj.GetMethodParameters("SetDNSServerSearchOrder");
                ib[
"DNSServerSearchOrder"]=new string[]{"202.103.44.150","202.103.24.68"};
                obj.InvokeMethod(
"SetDNSServerSearchOrder",ib,null);                
            }

        }

    }

}


 

用wmi出问题就用下面的

 

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Runtime.InteropServices;
using Microsoft.Win32;

namespace WindowsApplication2
{
    
/**//// <summary>
    
/// Form1 的摘要说明。
    
/// </summary>

    public class Form1 : System.Windows.Forms.Form
    
{
        
private System.Windows.Forms.TextBox textBox1;
        
private System.Windows.Forms.Button button1;
        
/**//// <summary>
        
/// 必需的设计器变量。
        
/// </summary>

        private System.ComponentModel.Container components = null;

        [DllImport(
"kernel32.dll",EntryPoint="SetComputerNameEx")] 
        
public static extern int apiSetComputerNameEx(int iType,string lpComputerName); //这个函数用来改计算机名

        [StructLayout(LayoutKind.Sequential, Pack 
= 1)]
            
internal struct TokPriv1Luid
        
{
            
public int Count;
            
public long Luid;
            
public int Attr;
        }


        [DllImport(
"kernel32.dll", ExactSpelling = true)]
        
internal static extern IntPtr GetCurrentProcess();
  
        [DllImport(
"advapi32.dll", ExactSpelling = true, SetLastError = true)]
        
internal static extern bool OpenProcessToken(IntPtr h, int acc, ref IntPtr phtok);
  
        [DllImport(
"advapi32.dll", SetLastError = true)]
        
internal static extern bool LookupPrivilegeValue(string host, string name, ref long pluid);
  
        [DllImport(
"advapi32.dll", ExactSpelling = true, SetLastError = true)]
        
internal static extern bool AdjustTokenPrivileges(IntPtr htok, bool disall,
            
ref TokPriv1Luid newst, int len, IntPtr prev, IntPtr relen);

        [DllImport(
"user32.dll")]
        
public static extern bool ExitWindowsEx(int uFlags, int dwReason);
        
internal const int SE_PRIVILEGE_ENABLED = 0x00000002;
        
internal const int TOKEN_QUERY = 0x00000008;
        
internal const int TOKEN_ADJUST_PRIVILEGES = 0x00000020;
        
internal const string SE_SHUTDOWN_NAME = "SeShutdownPrivilege";
        
internal const int EWX_LOGOFF = 0x00000000;
        
internal const int EWX_SHUTDOWN = 0x00000001;
        
internal const int EWX_REBOOT = 0x00000002;
        
internal const int EWX_FORCE = 0x00000004;
        
internal const int EWX_POWEROFF = 0x00000008;
        
internal const int EWX_FORCEIFHUNG = 0x00000010;

        
private static void DoExitWin(int DoFlag)
        
{

            
bool ok;
            TokPriv1Luid tp;
            IntPtr hproc 
= GetCurrentProcess();
            IntPtr htok 
= IntPtr.Zero;
            ok 
= OpenProcessToken(hproc, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, ref htok);
            tp.Count 
= 1;
            tp.Luid 
= 0;
            tp.Attr 
= SE_PRIVILEGE_ENABLED;
            ok 
= LookupPrivilegeValue(null, SE_SHUTDOWN_NAME, ref tp.Luid);
            ok 
= AdjustTokenPrivileges(htok, falseref tp, 0, IntPtr.Zero, IntPtr.Zero);
            ok 
= ExitWindowsEx(DoFlag, 0);
        }


        
public Form1()
        
{
            
//
            
// Windows 窗体设计器支持所必需的
            
//
            InitializeComponent();

            
//
            
// TODO: 在 InitializeComponent 调用后添加任何构造函数代码
            
//
        }


        
/**//// <summary>
        
/// 清理所有正在使用的资源。
        
/// </summary>

        protected override void Dispose( bool disposing )
        
{
            
if( disposing )
            
{
                
if (components != null
                
{
                    components.Dispose();
                }

            }

            
base.Dispose( disposing );
        }


        
/**//// <summary>
        
/// 设计器支持所需的方法 - 不要使用代码编辑器修改
        
/// 此方法的内容。
        
/// </summary>

        private void InitializeComponent()
        
{
            
this.textBox1 = new System.Windows.Forms.TextBox();
            
this.button1 = new System.Windows.Forms.Button();
            
this.SuspendLayout();
            
// 
            
// textBox1
            
// 
            this.textBox1.Location = new System.Drawing.Point(816);
            
this.textBox1.Name = "textBox1";
            
this.textBox1.TabIndex = 0;
            
this.textBox1.Text = "xxx";
            
// 
            
// button1
            
// 
            this.button1.Location = new System.Drawing.Point(1648);
            
this.button1.Name = "button1";
            
this.button1.TabIndex = 1;
            
this.button1.Text = "改IP";
            
this.button1.Click += new System.EventHandler(this.button1_Click);
            
// 
            
// Form1
            
// 
            this.AcceptButton = this.button1;
            
this.AutoScaleBaseSize = new System.Drawing.Size(614);
            
this.ClientSize = new System.Drawing.Size(12085);
            
this.Controls.Add(this.button1);
            
this.Controls.Add(this.textBox1);
            
this.Name = "Form1";
            
this.Text = "Form1";
            
this.ResumeLayout(false);

        }


        
/**//// <summary>
        
/// 应用程序的主入口点。
        
/// </summary>

        [STAThread]
        
static void Main() 
        
{
            Application.Run(
new Form1());
        }


        
private void button1_Click(object sender, System.EventArgs e)
        
{
            
this.chktb();
            DialogResult dr
=MessageBox.Show("提示","OK!",MessageBoxButtons.OK);
            
if(dr==DialogResult.OK)
                DoExitWin(EWX_FORCE 
| EWX_REBOOT);
        }

        
        
//这个函数主要是用来检查textbox里输入的内容.
        public void chktb()
        
{
            
string str=textBox1.Text;//计算机名
            string strip="";//IP的最后一位
            try
            
{
                
int a=int.Parse(str);
                strip
=str;
                
if(a>5811)
                
{
                    MessageBox.Show(
"输入的格式不对,请重新输入");
                    textBox1.Text
="";
                    
return;
                }

                
if(a<10)
                
{
                    str
="00"+a.ToString();
                }

                
else if(a<100)
                
{
                    str
="0"+a.ToString();
                }

                str
="XX"+str;            
            }

            
catch
            
{
                
switch(str)
                
{
                    
case "北京大学A":
                        str
="北京大学A";
                        strip
="166";
                        
break;
                    
case "北京大学B":
                        str
="北京大学B";
                        strip
="167";
                        
break;
                    
case "清华大学A":
                        str
="清华大学A";
                        strip
="174";
                        
break;
                    
case "清华大学B":
                        str
="清华大学B";
                        strip
="175";
                        
break;
                    
case "复旦大学A":
                        str
="复旦大学A";
                        strip
="168";
                        
break;
                    
case "复旦大学B":
                        str
="复旦大学B";
                        strip
="169";
                        
break;
                    
case "浙江大学A":
                        str
="浙江大学A";
                        strip
="176";
                        
break;
                    
case "浙江大学B":
                        str
="浙江大学B";
                        strip
="177";
                        
break;
                    
case "上海交大A":
                        str
="上海交大A";
                        strip
="180";
                        
break;
                    
case "上海交大B":
                        str
="上海交大B";
                        strip
="181";
                        
break;
                    
default:
                        MessageBox.Show(
"请输入正确的名字");
                        textBox1.Text
="";
                        
return;
                }

            }

            
//改计算机名,上面调用了一个winapi:setcomputernameEx
            apiSetComputerNameEx(5,str);
            
this.changenet(strip);
        }


        
//这个函数读取textbox里的内容,然后通过里面的内容来更改计算机的IP,网关,dns,及计算机名
        public void changenet(string strip)
        
{
            RegistryKey hklm
=Registry.LocalMachine;
            RegistryKey rkip
=hklm.CreateSubKey("System").CreateSubKey("CurrentControlSet").
                CreateSubKey(
"Services").CreateSubKey("Tcpip").CreateSubKey("Parameters").CreateSubKey("Interfaces");
            
string []strs=rkip.GetSubKeyNames();
            
foreach(string str in strs)
            
{
                
if(rkip.OpenSubKey(str).GetValue("AddressType")==null)
                    
continue;
                rkip.CreateSubKey(str).SetValue(
"DefaultGateway",new string[]{"192.168.0.1"});
                
if(int.Parse(strip)>200)//当计算机的名字大于200号的时候,自动将IP的第三位改成1;
                {
                    
string[] ipstrs={"192.168.1."+int.Parse(strip.Substring(1,2)).ToString()};
                    rkip.CreateSubKey(str).SetValue(
"IPAddress",ipstrs);
                }

                
else
                
{
                    
string[] ipstrs={"192.168.0."+int.Parse(strip).ToString()};
                    rkip.CreateSubKey(str).SetValue(
"IPAddress",ipstrs);
                }
                
                rkip.CreateSubKey(str).SetValue(
"NameServer","202.103.44.150,202.103.24.68");
                rkip.CreateSubKey(str).SetValue(
"SubnetMask",new string[]{"255.255.248.0"});
            }

        }

    }

}


 

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值