C# 设置IP地址及设置自动获取IP

原文:C# 设置IP地址及设置自动获取IP

</pre><pre name="code" class="csharp">1.添加引用"system.Management"
2.添加using System.Management
</pre><pre name="code" class="csharp">using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Management;

namespace IPChange
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        static void SetNetworkAdapter()
        {
            ManagementBaseObject inPar = null;
            ManagementBaseObject outPar = null;
            ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
            ManagementObjectCollection moc = mc.GetInstances();
            foreach (ManagementObject mo in moc)
            {
                if (!(bool)mo["IPEnabled"])
                    continue;
                inPar = mo.GetMethodParameters("EnableStatic");
                inPar["IPAddress"] = new string[] { "172.17.123.154"};
                inPar["SubnetMask"] = new string[] { "255.255.255.0"};
                outPar = mo.InvokeMethod("EnableStatic", inPar, null);
                inPar = mo.GetMethodParameters("SetGateways");
                inPar["DefaultIPGateway"] = new string[] { "172.17.123.254"};
                outPar = mo.InvokeMethod("SetGateways", inPar, null);
                inPar = mo.GetMethodParameters("SetDNSServerSearchOrder");
                inPar["DNSServerSearchOrder"] = new string[] { "211.137.241.34", "202.97.224.69" }; 
                outPar = mo.InvokeMethod("SetDNSServerSearchOrder", inPar, null);
                break;
            }
        }


        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {
            SetNetworkAdapter();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
            ManagementObjectCollection moc = mc.GetInstances();
            foreach (ManagementObject mo in moc)
            {
                if (!(bool)mo["IPEnabled"]) continue;
                mo.InvokeMethod("SetDNSServerSearchOrder", null);
                mo.InvokeMethod("EnableStatic", null);
                mo.InvokeMethod("SetGateways", null);
                mo.InvokeMethod("EnableDHCP", null);
                break;
            }
        }
    }
}

上一篇:提升用户体验!29个使用动画效果的网站布局


下一篇:小计使用多线程和gevent来提高celery性能及稳定性