c#修改本地连接工具 ip地址,dns,网关,子网掩码

时间:2022-09-04 22:41:02

//Form1类后台    

#region 加载配置文件中的信息
        /// <summary>
        /// 加载配置文件中的信息
        /// </summary>
        protected void loadConfig()
        {
            cf.fileName = AppDomain.CurrentDomain.BaseDirectory + "\\config.ini";
            txtIP.Text = cf["ip地址"];
            txtSubMark.Text = cf["子网掩码"];
            txtGateWay.Text = cf["默认网关"];
            txtDNS1.Text = cf["主DNS"];
            txtDNS2.Text = cf["备用DNS"];
        }
        #endregion

#region 设置ip信息到网卡
        private void btnSettingNetwork_Click(object sender, EventArgs e)
        {
           
            try
            {
                if (!IsIpaddress(txtIP.Text.Trim()))
                {
                    MessageBox.Show("ip格式不正确!"); return;
                }
                if (!IsIpaddress(txtSubMark.Text.Trim()))
                {
                    MessageBox.Show("子网掩码格式不正确!"); return;
                }
                if (!IsIpaddress(txtGateWay.Text.Trim()))
                {
                    MessageBox.Show("网关格式不正确!"); return;
                }
                if (!IsIpaddress(txtDNS1.Text.Trim()))
                {
                    MessageBox.Show("DNS1格式不正确!"); return;
                }
                if (!IsIpaddress(txtDNS2.Text.Trim()))
                {
                    MessageBox.Show("DNS2格式不正确!"); return;
                }
                string[] ip = new string[] {txtIP.Text.Trim() };
                string[] SubMark = new string[] {txtSubMark.Text.Trim() };
                string[] GateWay = new string[] {txtGateWay.Text.Trim() };
                string[] DNS = new string[] {txtDNS1.Text.Trim(),txtDNS2.Text.Trim() };
                SetIpInfo(ip, SubMark, GateWay, DNS);
                cf["ip地址"] = txtIP.Text.Trim();
                cf["子网掩码"] = txtSubMark.Text.Trim();
                cf["默认网关"] = txtGateWay.Text.Trim();
                cf["主DNS"] = txtDNS1.Text.Trim();
                cf["备用DNS"] = txtDNS2.Text.Trim();
                MessageBox.Show("ip信息设置成功!","成功提示",MessageBoxButtons.OK,MessageBoxIcon.Information);
            }
            catch(Exception er)
            {
                MessageBox.Show("设置出错:"+er.Message,"出错提示",MessageBoxButtons.OK,MessageBoxIcon.Error);
            }
        }

protected void SetIpInfo(string []ip,string []SubMark,string []GateWay,string []DNS)
        {
            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"] = ip;//ip地址
                inPar["SubnetMask"] =SubMark; //子网掩码
                mo.InvokeMethod("EnableStatic", inPar, null);//执行

inPar = mo.GetMethodParameters("SetGateways");
                inPar["DefaultIPGateway"] = GateWay; //设置网关地址 1.网关;2.备用网关
                outPar = mo.InvokeMethod("SetGateways", inPar, null);//执行

inPar = mo.GetMethodParameters("SetDNSServerSearchOrder");
                inPar["DNSServerSearchOrder"] = DNS; //设置DNS  1.DNS 2.备用DNS
                mo.InvokeMethod("SetDNSServerSearchOrder", inPar, null);// 执行
                break; //只设置一张网卡,不能多张。
            }
        }

#endregion

#region 从网卡获取ip设置信息
        /// <summary>
        /// 从网卡获取ip设置信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnGetFromNetwork_Click(object sender, EventArgs e)
        {
            NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
            foreach (NetworkInterface adapter in nics)
            {
                bool Pd1 = (adapter.NetworkInterfaceType == NetworkInterfaceType.Ethernet); //判断是否是以太网连接
                if (Pd1)
                {
                    IPInterfaceProperties ip = adapter.GetIPProperties();     //IP配置信息
                    if (ip.UnicastAddresses.Count > 0)
                    {
                        txtIP.Text = ip.UnicastAddresses[0].Address.ToString();//IP地址
                        txtSubMark.Text = ip.UnicastAddresses[0].IPv4Mask.ToString();//子网掩码

}
                    if (ip.GatewayAddresses.Count > 0)
                    {
                        txtGateWay.Text = ip.GatewayAddresses[0].Address.ToString();//默认网关
                    }
                    int DnsCount = ip.DnsAddresses.Count;
                    Console.WriteLine("DNS服务器地址:");
                    if (DnsCount > 0)
                    {
                        try
                        {
                            txtDNS1.Text = ip.DnsAddresses[0].ToString(); //主DNS
                            txtDNS2.Text = ip.DnsAddresses[1].ToString(); //备用DNS地址
                        }
                        catch(Exception er)
                        {
                            throw er;
                        }
                    }
                }
            }
        }
        #endregion

#region 判断是否是正确的ip地址
        /// <summary>
        /// 判断是否是正确的ip地址
        /// </summary>
        /// <param name="ipaddress"></param>
        /// <returns></returns>
        protected bool IsIpaddress(string ipaddress)
        {
            string[] nums = ipaddress.Split('.');
            if (nums.Length != 4) return false;
            foreach (string num in nums)
            {
                if ( Convert.ToInt32(num) < 0 || Convert.ToInt32(num) > 255) return false;
            }
            return true;
        }
        #endregion

#region Form1_Load
        private void Form1_Load(object sender, EventArgs e)
        {
            loadConfig();
        }
        #endregion

//config类

public class ConfigFile : IConfig
    {
        // Fields
        private string _fileName;
        private static ConfigFile _Instance;

// Methods
        private ConfigFile()
        {
        }

public bool CreateFile()
        {
            bool flag = false;
            if (File.Exists(this.fileName))
            {
                return flag;
            }
            using (File.Create(this.fileName))
            {
            }
            return true;
        }

public bool KeyExists(string Key)
        {
            return (this.Keys as ICollection<string>).Contains(Key);
        }

// Properties
        public string fileName
        {
            get
            {
                return this._fileName;
            }
            set
            {
                this._fileName = value;
            }
        }

public static ConfigFile Instanse
        {
            get
            {
                if (_Instance == null)
                {
                    _Instance = new ConfigFile();
                }
                return _Instance;
            }
        }

public string this[string Key]
        {
            get
            {
                if (!this.CreateFile())
                {
                    foreach (string str in File.ReadAllLines(this.fileName, Encoding.UTF8))
                    {
                        Match match = Regex.Match(str, @"(\w+)=([\w\W]+)");
                        string str2 = match.Groups[1].Value;
                        string str3 = match.Groups[2].Value;
                        if (str2 == Key)
                        {
                            return str3;
                        }
                    }
                }
                return "";
            }
            set
            {
                if (this.CreateFile())
                {
                    File.AppendAllText(this.fileName, Key + "=" + value + "\r\n");
                }
                else
                {
                    string[] contents = File.ReadAllLines(this.fileName, Encoding.UTF8);
                    for (int i = 0; i < contents.Length; i++)
                    {
                        string input = contents[i];
                        Match match = Regex.Match(input, @"(\w+)=(\w+)");
                        string str2 = match.Groups[1].Value;
                        string text1 = match.Groups[2].Value;
                        if (str2 == Key)
                        {
                            contents[i] = str2 + "=" + value;
                            File.WriteAllLines(this.fileName, contents);
                            return;
                        }
                    }
                    File.AppendAllText(this.fileName, Key + "=" + value + "\r\n");
                }
            }
        }

public string[] Keys
        {
            get
            {
                List<string> list = new List<string>();
                if (!this.CreateFile())
                {
                    foreach (string str in File.ReadAllLines(this.fileName, Encoding.UTF8))
                    {
                        string item = Regex.Match(str, @"(\w+)=(\w+)").Groups[1].Value;
                        list.Add(item);
                    }
                }
                return list.ToArray();
            }
        }
    }

public interface IConfig
    {
        // Methods
        bool KeyExists(string Key);

// Properties
        string this[string Key] { get; set; }
        string[] Keys { get; }
    }

效果:

c#修改本地连接工具  ip地址,dns,网关,子网掩码

c#修改本地连接工具 ip地址,dns,网关,子网掩码的更多相关文章

  1. CentOS 网络设置修改 指定IP地址 DNS 网关(转)

    CentOS 网络设置修改 指定IP地址 DNS 网关(实测 笔记)   环境: 系统硬件:vmware vsphere (CPU:2*4核,内存2G) 系统版本:Centos-6.5-x86_64 ...

  2. CentOS 修改IP地址&comma; DNS&comma; 网关

    一.CentOS 修改IP地址 修改对应网卡的IP地址的配置文件# vi /etc/sysconfig/network-scripts/ifcfg-eth0 修改以下内容DEVICE=eth0 #描述 ...

  3. CentOS 6 网络设置修改 指定IP地址 DNS 网关

    环境: 系统硬件:vmware vsphere (CPU:2*4核,内存2G) 系统版本:Centos-6.5-x86_64 路由器网关:192.168.1.1 步骤: 1.查看网络MAC地址 [ro ...

  4. Linux系统下修改IP地址、网关、DNS的基本方法

    临时修改IP地址.网关.主机名.DNS,马上生效,无需重启(重启后失效) 1.修改主机名 #hostname Slyar 2.修改IP地址(eth0为网卡名称) #ifconfig eth0 192. ...

  5. Linux学习笔记(10)linux网络管理与配置之一——主机名与IP地址&comma;DNS解析与本地hosts解析(1-4)

    Linux学习笔记(10)linux网络管理与配置之一——主机名与IP地址,DNS解析与本地hosts解析 大纲目录 0.常用linux基础网络命令 1.配置主机名 2.配置网卡信息与IP地址 3.配 ...

  6. linux下设置ip地址 gw网关&comma;dns的方法

    本文介绍下,在linux中设置IP地址.网关.dns的方法,有需要的朋友作个参考吧.   设置linux网络的方法有两种:第一种:使用命令修改(直接即时生效) 复制代码代码示例: ip and net ...

  7. Linux 修改 IP地址 和 网关

    修改IP地址和网关是很常见的操作,在做相关实验的时候,如果没有设置好,会带来很多不必要的麻烦.. 1. 修改IP地址vi /etc/sysconfig/network-scripts/ifcfg-et ...

  8. IP:192&period;168&period;21&period;173 子网掩码:255&period;255&period;255&period;0 网关:192&period;168&period;21&period;2 DNS:8&period;8&period;8&period;8 8&period;8&period;4&period;4 1、设置IP地址、网关 ee &sol;etc&sol;rc&period;conf &num;编辑 ifconfig&lowbar;em0&equals;&quot&semi;inet 192&period;168&period;21&period;173 netmask 255

    IP:192.168.21.173子网掩码:255.255.255.0网关:192.168.21.2DNS:8.8.8.88.8.4.41.设置IP地址.网关ee /etc/rc.conf #编辑if ...

  9. IP地址&sol;掩码&sol;网关&sol;DNS的设置与工作原理(转)

    现在互联网飞速发展,工作中生活中上不了网的计算机是不可想象的,而电脑系统网络设置中的IP地址.子网掩码.默认网关及DNS服务器,怎么理解,它们是如何工作的,下面做个简单介绍. 通常的上网方式,是打开I ...

随机推荐

  1. meta 360极速模式

    <meta name="render" content="webkit">  启用360极速模式

  2. 从0开始学java——JSP&amp&semi;Servlet——web容器搜索class的路径顺序

    在web应用程序如果要用到某个类,会按照如下的顺序来搜索: 1)在WEB-INF/classes目录下搜索: 2)如果该目录下没有,则会到WEB-INF/lib目录下的jar文件中搜索: 3)如果还没 ...

  3. VS2015 Cordova Ionic移动开发(五)

    一.创建侧边菜单和导航项目 1.使用VS创建一个Ionic空项目,同时创建一个Ionic SideMenu和Ionic Tabs项目.将SideMenu和Tabs项目里的templates和js文件合 ...

  4. Omi全新版本来袭 - 指令系统

    写在前面 Omi框架到目前为止有三种版本. omi.js 使用 sodajs 为内置指令系统 omi.lite.js 不包含任何模板引擎 omi.mustache.js 使用 mustache.js为 ...

  5. python学习之数字

    数字python中的数字比较典型,典型在可以表示很小的数,也可以表示很大的数,c语言的数字类型如果表示很大的数的话,可能会报溢出错误,但是python不会,python 数字类型的完整工具包括整数和浮 ...

  6. ActiveMQ系列之二:ActiveMQ安装和基本使用

    下载并安装ActiveMQ服务器端 1:从http://activemq.apache.org/download.html下载最新的ActiveMQ 2:直接解压,然后拷贝到你要安装的位置就好了 启动 ...

  7. Nginx 过滤sub模块

    L70 通过 --with-http_sub_module 编译进nginx sub_filter 指令 Syntax: sub_filter string replacement; Default: ...

  8. 通过编写一个简单的日志类库来加深了解C&num;的文件访问控制

    在程序的开发调试过程及发布运行后的状态监控中,日志都有着极其重要的分量,通过在关键逻辑节点将关键数据记录到日志文件当中能帮助我们尽快找到程序问题所在.网上有不少专业成熟的日志组件可用,比如log4ne ...

  9. Mybatis框架七:三种方式整合Spring

    需要的jar包: 新建lib文件夹放入jar包,Build Path-->Add To Build Path之后: 原始Dao开发示例: src下:新建核心配置文件sqlMapConfig.xm ...

  10. EntityFramework Core问题处理集锦(一)

    前言 和大家脱离了一段时间,有时候总想着时间挤挤总是会有的,但是并非人愿,后面会借助周末的时间来打理博客,如有问题可以在周末私信我或者加我QQ皆可,欢迎和大家一起探讨,本节我们来讨论EF Core中的 ...