c#获取和设置网卡ip/dns等信息

简介:   using System; using System.Windows.Forms; using System.Management; using System.

 

using System;
using System.Windows.Forms;
using System.Management;
using System.Net.NetworkInformation;
using System.Text.RegularExpressions;

namespace 修改本地连接工具
{
    public partial class Form1 : Form
    {
        ConfigFile cf = ConfigFile.Instanse;
            
        public Form1()
        {
            InitializeComponent();
            
        }

        #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

    }
}


 

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Text.RegularExpressions;

namespace 修改本地连接工具
{
    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; }
    }
}

 


运行:

 

 

相关文章
|
监控 负载均衡 安全
静态IP代理与动态IP代理:提升速度与保障隐私的技术解析
本文探讨了静态IP代理和动态IP代理的特性和应用场景。静态IP代理通过高质量服务提供商、网络设置优化、定期更换IP与负载均衡及性能监控提升网络访问速度;动态IP代理则通过隐藏真实IP、增强安全性、绕过封锁和提供独立IP保障用户隐私。结合实际案例与代码示例,展示了两者在不同场景下的优势,帮助用户根据需求选择合适的代理服务以实现高效、安全的网络访问。
478 1
|
Serverless 对象存储 人工智能
智能文件解析:体验阿里云多模态信息提取解决方案
在当今数据驱动的时代,信息的获取和处理效率直接影响着企业决策的速度和质量。然而,面对日益多样化的文件格式(文本、图像、音频、视频),传统的处理方法显然已经无法满足需求。
540 4
智能文件解析:体验阿里云多模态信息提取解决方案
|
文字识别 开发者 数据处理
多模态数据信息提取解决方案评测报告!
阿里云推出的《多模态数据信息提取》解决方案,利用AI技术从文本、图像、音频和视频中提取关键信息,支持多种应用场景,大幅提升数据处理效率。评测涵盖部署体验、文档清晰度、模板简化、示例验证及需求适配性等方面。方案表现出色,部署简单直观,功能强大,适合多种业务场景。建议增加交互提示、多语言支持及优化OCR和音频转写功能...
496 3
多模态数据信息提取解决方案评测报告!
|
网络协议 Unix Linux
深入解析:Linux网络配置工具ifconfig与ip命令的全面对比
虽然 `ifconfig`作为一个经典的网络配置工具,简单易用,但其功能已经不能满足现代网络配置的需求。相比之下,`ip`命令不仅功能全面,而且提供了一致且简洁的语法,适用于各种网络配置场景。因此,在实际使用中,推荐逐步过渡到 `ip`命令,以更好地适应现代网络管理需求。
792 11
|
机器学习/深度学习 人工智能 文字识别
从“泛读”到“精读”:合合信息文档解析如何让大模型更懂复杂文档?
随着deepseek等大模型逐渐步入视野,理论上文档解析工作应能大幅简化。 然而,实际情况却不尽如人意。当前的多模态大模型虽然具备强大的视觉与语言交互能力,但在解析非结构化文档时,仍面临复杂版式、多元素混排以及严密逻辑推理等挑战。
481 0
|
数据采集 XML API
深入解析BeautifulSoup:从sohu.com视频页面提取关键信息的实战技巧
深入解析BeautifulSoup:从sohu.com视频页面提取关键信息的实战技巧
|
自然语言处理 数据可视化 前端开发
从数据提取到管理:合合信息的智能文档处理全方位解析【合合信息智能文档处理百宝箱】
合合信息的智能文档处理“百宝箱”涵盖文档解析、向量化模型、测评工具等,解决了复杂文档解析、大模型问答幻觉、文档解析效果评估、知识库搭建、多语言文档翻译等问题。通过可视化解析工具 TextIn ParseX、向量化模型 acge-embedding 和文档解析测评工具 markdown_tester,百宝箱提升了文档处理的效率和精确度,适用于多种文档格式和语言环境,助力企业实现高效的信息管理和业务支持。
从数据提取到管理:合合信息的智能文档处理全方位解析【合合信息智能文档处理百宝箱】
|
域名解析 网络协议 测试技术
IP、掩码、网关、DNS1、DNS2到底是什么东西,ping telnet测试
理解IP地址、子网掩码、默认网关和DNS服务器的概念是有效管理和配置网络的基础。通过使用ping和telnet命令,可以测试网络连通性和服务状态,快速诊断和解决网络问题。这些工具和概念是网络管理员和IT专业人员日常工作中不可或缺的部分。希望本文提供的详细解释和示例能够帮助您更好地理解和应用这些网络配置和测试工具。
8996 2
|
人工智能 前端开发 JavaScript
拿下奇怪的前端报错(一):报错信息是一个看不懂的数字数组Buffer(475) [Uint8Array],让AI大模型帮忙解析
本文介绍了前端开发中遇到的奇怪报错问题,特别是当错误信息不明确时的处理方法。作者分享了自己通过还原代码、试错等方式解决问题的经验,并以一个Vue3+TypeScript项目的构建失败为例,详细解析了如何从错误信息中定位问题,最终通过解读错误信息中的ASCII码找到了具体的错误文件。文章强调了基础知识的重要性,并鼓励读者遇到类似问题时不要慌张,耐心分析。
684 5
|
算法 测试技术 C语言
深入理解HTTP/2:nghttp2库源码解析及客户端实现示例
通过解析nghttp2库的源码和实现一个简单的HTTP/2客户端示例,本文详细介绍了HTTP/2的关键特性和nghttp2的核心实现。了解这些内容可以帮助开发者更好地理解HTTP/2协议,提高Web应用的性能和用户体验。对于实际开发中的应用,可以根据需要进一步优化和扩展代码,以满足具体需求。
1290 29

相关产品

  • 云解析DNS
  • 推荐镜像

    更多
  • DNS