C# 小工具开源分享之本机IP修改器

前言

工作中,总有修改本机IP的需求,一直都是手动去改,直到坚持不住了……

一个修改IP的小工具开源给大家,地址:https://github.com/hxsfx/hxsfx_IPSet

一、工具演示

01、软件界面.png

选择需要设置的网络(适配器名称),然后根据实际情况设置IP、掩码以及网关,然后点击修改,当出现如下弹框即代表修改成功:

02、修改成功提示弹窗.png

提示:弹窗内容会根据输入的IP等信息发生变化

二、主要代码

1、主要通过NetworkInterface类获取适配器列表

/// <summary>
/// 初始化适配器(以太网)名称列表
/// </summary>
private void InitalNetworkInterfaceName()
{
    this.NetworkInterfaces = NetworkInterface.GetAllNetworkInterfaces();
    foreach (var adapter in this.NetworkInterfaces)
    {
        if (adapter.OperationalStatus == OperationalStatus.Up)
        {
            if (adapter.NetworkInterfaceType == NetworkInterfaceType.Ethernet
            || adapter.NetworkInterfaceType == NetworkInterfaceType.Wireless80211)
            {
                this.cb_adapter.Items.Add(adapter.Name);
            }
        }
    }
    if (this.cb_adapter.Items.Count > 0)
    {
        this.cb_adapter.SelectedIndex = 0;
    }
}

2、通过GetIPProperties()方法获取IP地址、掩码及网关

private void cb_adapter_SelectedIndexChanged(object sender, EventArgs e)
{
    foreach (var adapter in NetworkInterfaces)
    {
        if (adapter.Name == (string)this.cb_adapter.SelectedItem)
        {
            var p = adapter.GetIPProperties();
            var gatewayCollection = p.GatewayAddresses;
            if (gatewayCollection.Count > 0)
            {
                this.textBox_gateway.Text = gatewayCollection[0].Address.ToString();
            }
            var ipCollection = p.UnicastAddresses;
            if (ipCollection.Count > 0)
            {
                this.textBox_ip.Text = ipCollection[1].Address.ToString();
                var ipv4Mask = ipCollection[1].IPv4Mask;
                this.textBox_maskCode.Text = ipv4Mask == null ? "" : ipv4Mask.ToString();
            }
            break;
        }
    }
}

三、完整代码

1、Form1.cs

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net.NetworkInformation;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace hxsfxIPSet
{
    public partial class Form1 : Form
    {
        public NetworkInterface[] NetworkInterfaces { get; set; }
        public Form1()
        {
            InitializeComponent();
            InitalNetworkInterfaceName();
        }
        #region 按住标题拖动窗体
        [DllImport("user32.dll")]
        public static extern bool ReleaseCapture();
        [DllImport("user32.dll")]
        public static extern bool SendMessage(IntPtr hwnd, int wMsg, int wParam, int lParam);
        public const int WM_SYSCOMMAND = 0x0112;
        public const int SC_MOVE = 0xF010;
        public const int HTCAPTION = 0x0002;
        private void lb_title_MouseDown(object sender, MouseEventArgs e)
        {
            ReleaseCapture();
            SendMessage(this.Handle, WM_SYSCOMMAND, SC_MOVE + HTCAPTION, 0);
        }
        #endregion
        /// <summary>
        /// 初始化适配器(以太网)名称列表
        /// </summary>
        private void InitalNetworkInterfaceName()
        {
            this.NetworkInterfaces = NetworkInterface.GetAllNetworkInterfaces();
            foreach (var adapter in this.NetworkInterfaces)
            {
                if (adapter.OperationalStatus == OperationalStatus.Up)
                {
                    if (adapter.NetworkInterfaceType == NetworkInterfaceType.Ethernet
                    || adapter.NetworkInterfaceType == NetworkInterfaceType.Wireless80211)
                    {
                        this.cb_adapter.Items.Add(adapter.Name);
                    }
                }
            }
            if (this.cb_adapter.Items.Count > 0)
            {
                this.cb_adapter.SelectedIndex = 0;
            }
        }
        private void cb_adapter_SelectedIndexChanged(object sender, EventArgs e)
        {
            foreach (var adapter in NetworkInterfaces)
            {
                if (adapter.Name == (string)this.cb_adapter.SelectedItem)
                {
                    var p = adapter.GetIPProperties();
                    var gatewayCollection = p.GatewayAddresses;
                    if (gatewayCollection.Count > 0)
                    {
                        this.textBox_gateway.Text = gatewayCollection[0].Address.ToString();
                    }
                    var ipCollection = p.UnicastAddresses;
                    if (ipCollection.Count > 0)
                    {
                        this.textBox_ip.Text = ipCollection[1].Address.ToString();
                        var ipv4Mask = ipCollection[1].IPv4Mask;
                        this.textBox_maskCode.Text = ipv4Mask == null ? "" : ipv4Mask.ToString();
                    }
                    break;
                }
            }
        }
        private void btn_getNetworkInterfaceName_Click(object sender, EventArgs e)
        {
            this.cb_adapter.SelectedIndex = -1;
            InitalNetworkInterfaceName();
        }
        private void btn_modify_Click(object sender, EventArgs e)
        {
            using (Process process = new System.Diagnostics.Process())
            {
                process.StartInfo.FileName = "cmd.exe";
                //是否使用操作系统shell启动
                process.StartInfo.UseShellExecute = false;
                //接受来自调用程序的输入信息
                process.StartInfo.RedirectStandardInput = true;
                //由调用程序获取输出信息
                process.StartInfo.RedirectStandardOutput = true;
                //不显示程序窗口
                process.StartInfo.CreateNoWindow = true;
                process.Start();
                //向cmd窗口发送输入信息
                process.StandardInput.WriteLine($"netsh interface ip set address name=\"{(string)this.cb_adapter.SelectedItem}\" source=static addr={this.textBox_ip.Text} mask={this.textBox_maskCode.Text} gateway={this.textBox_gateway.Text} gwmetric=1&exit");
                process.StandardInput.AutoFlush = true;
                //获取cmd窗口的输出信息
                var outputList = new List<string>();
                string output = process.StandardOutput.ReadLine();
                while (output != null)
                {
                    output = process.StandardOutput.ReadLine();
                    if (output != null)
                    {
                        outputList.Add(output);
                    }
                }
                MessageBox.Show(string.Join("\r\n", outputList.ToArray()));
                process.WaitForExit();//等待程序执行完退出进程
            }
        }
        private void button_closeForm_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }
    }
}

2、Form1.Designer.cs

namespace hxsfxIPSet
{
    partial class Form1
    {
        /// <summary>
        /// 必需的设计器变量。
        /// </summary>
        private System.ComponentModel.IContainer components = null;
        /// <summary>
        /// 清理所有正在使用的资源。
        /// </summary>
        /// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }
        #region Windows 窗体设计器生成的代码
        /// <summary>
        /// 设计器支持所需的方法 - 不要修改
        /// 使用代码编辑器修改此方法的内容。
        /// </summary>
        private void InitializeComponent()
        {
            this.label1 = new System.Windows.Forms.Label();
            this.label2 = new System.Windows.Forms.Label();
            this.label3 = new System.Windows.Forms.Label();
            this.label4 = new System.Windows.Forms.Label();
            this.textBox_ip = new System.Windows.Forms.TextBox();
            this.textBox_maskCode = new System.Windows.Forms.TextBox();
            this.textBox_gateway = new System.Windows.Forms.TextBox();
            this.btn_modify = new System.Windows.Forms.Button();
            this.cb_adapter = new System.Windows.Forms.ComboBox();
            this.lb_title = new System.Windows.Forms.Label();
            this.button_closeForm = new System.Windows.Forms.Button();
            this.btn_getNetworkInterfaceName = new System.Windows.Forms.Button();
            this.SuspendLayout();
            //
            // label1
            //
            this.label1.AutoSize = true;
            this.label1.Location = new System.Drawing.Point(13, 33);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(101, 12);
            this.label1.TabIndex = 0;
            this.label1.Text = "网络适配器名称:";
            //
            // label2
            //
            this.label2.AutoSize = true;
            this.label2.Location = new System.Drawing.Point(13, 73);
            this.label2.Name = "label2";
            this.label2.Size = new System.Drawing.Size(29, 12);
            this.label2.TabIndex = 2;
            this.label2.Text = "IP:";
            //
            // label3
            //
            this.label3.AutoSize = true;
            this.label3.Location = new System.Drawing.Point(13, 112);
            this.label3.Name = "label3";
            this.label3.Size = new System.Drawing.Size(41, 12);
            this.label3.TabIndex = 3;
            this.label3.Text = "掩码:";
            //
            // label4
            //
            this.label4.AutoSize = true;
            this.label4.Location = new System.Drawing.Point(13, 151);
            this.label4.Name = "label4";
            this.label4.Size = new System.Drawing.Size(41, 12);
            this.label4.TabIndex = 4;
            this.label4.Text = "网关:";
            //
            // textBox_ip
            //
            this.textBox_ip.Location = new System.Drawing.Point(13, 88);
            this.textBox_ip.Name = "textBox_ip";
            this.textBox_ip.Size = new System.Drawing.Size(205, 21);
            this.textBox_ip.TabIndex = 5;
            this.textBox_ip.TextChanged += new System.EventHandler(this.textBox_ip_TextChanged);
            //
            // textBox_maskCode
            //
            this.textBox_maskCode.Location = new System.Drawing.Point(14, 127);
            this.textBox_maskCode.Name = "textBox_maskCode";
            this.textBox_maskCode.Size = new System.Drawing.Size(204, 21);
            this.textBox_maskCode.TabIndex = 6;
            //
            // textBox_gateway
            //
            this.textBox_gateway.Location = new System.Drawing.Point(14, 166);
            this.textBox_gateway.Name = "textBox_gateway";
            this.textBox_gateway.Size = new System.Drawing.Size(204, 21);
            this.textBox_gateway.TabIndex = 7;
            //
            // btn_modify
            //
            this.btn_modify.BackColor = System.Drawing.Color.White;
            this.btn_modify.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
            this.btn_modify.Location = new System.Drawing.Point(15, 193);
            this.btn_modify.Name = "btn_modify";
            this.btn_modify.Size = new System.Drawing.Size(203, 30);
            this.btn_modify.TabIndex = 8;
            this.btn_modify.Text = "点击修改";
            this.btn_modify.UseVisualStyleBackColor = false;
            this.btn_modify.Click += new System.EventHandler(this.btn_modify_Click);
            //
            // cb_adapter
            //
            this.cb_adapter.FormattingEnabled = true;
            this.cb_adapter.Location = new System.Drawing.Point(15, 50);
            this.cb_adapter.Name = "cb_adapter";
            this.cb_adapter.Size = new System.Drawing.Size(144, 20);
            this.cb_adapter.TabIndex = 10;
            this.cb_adapter.SelectedIndexChanged += new System.EventHandler(this.cb_adapter_SelectedIndexChanged);
            //
            // lb_title
            //
            this.lb_title.Dock = System.Windows.Forms.DockStyle.Top;
            this.lb_title.Font = new System.Drawing.Font("宋体", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
            this.lb_title.Location = new System.Drawing.Point(0, 0);
            this.lb_title.Name = "lb_title";
            this.lb_title.Size = new System.Drawing.Size(230, 24);
            this.lb_title.TabIndex = 11;
            this.lb_title.Text = " HXSFX · IP修改";
            this.lb_title.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
            this.lb_title.MouseDown += new System.Windows.Forms.MouseEventHandler(this.lb_title_MouseDown);
            //
            // button_closeForm
            //
            this.button_closeForm.Cursor = System.Windows.Forms.Cursors.Hand;
            this.button_closeForm.FlatAppearance.BorderSize = 0;
            this.button_closeForm.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
            this.button_closeForm.Location = new System.Drawing.Point(206, -1);
            this.button_closeForm.Name = "button_closeForm";
            this.button_closeForm.Size = new System.Drawing.Size(25, 25);
            this.button_closeForm.TabIndex = 12;
            this.button_closeForm.Text = "×";
            this.button_closeForm.UseVisualStyleBackColor = true;
            this.button_closeForm.Click += new System.EventHandler(this.button_closeForm_Click);
            //
            // btn_getNetworkInterfaceName
            //
            this.btn_getNetworkInterfaceName.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
            this.btn_getNetworkInterfaceName.Font = new System.Drawing.Font("宋体", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
            this.btn_getNetworkInterfaceName.Location = new System.Drawing.Point(166, 50);
            this.btn_getNetworkInterfaceName.Name = "btn_getNetworkInterfaceName";
            this.btn_getNetworkInterfaceName.Size = new System.Drawing.Size(52, 20);
            this.btn_getNetworkInterfaceName.TabIndex = 13;
            this.btn_getNetworkInterfaceName.Text = "刷新";
            this.btn_getNetworkInterfaceName.UseVisualStyleBackColor = true;
            this.btn_getNetworkInterfaceName.Click += new System.EventHandler(this.btn_getNetworkInterfaceName_Click);
            //
            // Form1
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(230, 230);
            this.Controls.Add(this.btn_getNetworkInterfaceName);
            this.Controls.Add(this.button_closeForm);
            this.Controls.Add(this.lb_title);
            this.Controls.Add(this.cb_adapter);
            this.Controls.Add(this.btn_modify);
            this.Controls.Add(this.textBox_gateway);
            this.Controls.Add(this.textBox_maskCode);
            this.Controls.Add(this.textBox_ip);
            this.Controls.Add(this.label4);
            this.Controls.Add(this.label3);
            this.Controls.Add(this.label2);
            this.Controls.Add(this.label1);
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
            this.Name = "Form1";
            this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
            this.ResumeLayout(false);
            this.PerformLayout();
        }
        #endregion
        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.Label label2;
        private System.Windows.Forms.Label label3;
        private System.Windows.Forms.Label label4;
        private System.Windows.Forms.TextBox textBox_ip;
        private System.Windows.Forms.TextBox textBox_maskCode;
        private System.Windows.Forms.TextBox textBox_gateway;
        private System.Windows.Forms.Button btn_modify;
        private System.Windows.Forms.ComboBox cb_adapter;
        private System.Windows.Forms.Label lb_title;
        private System.Windows.Forms.Button button_closeForm;
        private System.Windows.Forms.Button btn_getNetworkInterfaceName;
    }
}
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 218,858评论 6 508
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,372评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 165,282评论 0 356
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,842评论 1 295
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,857评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,679评论 1 305
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,406评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,311评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,767评论 1 315
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,945评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,090评论 1 350
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,785评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,420评论 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,988评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,101评论 1 271
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,298评论 3 372
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,033评论 2 355

推荐阅读更多精彩内容