C#获取本机网络连接名,获取和设置IP地址

C#获取本机网络连接名,获取和设置IP地址C#获取本机网络连接名,获取和设置IP地址usingSystem;usingSystem.Collections.Generic;usingSystem.ComponentModel;usingSystem.Data;usingSystem.Drawing;usingSystem.Linq;usingSystem.Text;usingSystem.Windows.Forms;usingSystem.Management;usingSystem.IO;namesp

C#获取本机网络连接名,获取和设置IP地址,使用WMI接口

新建windowsForm应用程序GetAndSetIpAddressDemo,将默认的窗体Form1重命名为FormGetAndSetIP。添加对System.Management 类库的引用。

窗体设计FormGetAndSetIP如图:

C#获取本机网络连接名,获取和设置IP地址

主要源程序如下(忽略自动生成的事件等代码):

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Management;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

/*
 * DHCP(Dynamic Host Configuration Protocol),动态主机配置协议,是一个应用层协议。
 * 当我们将客户主机ip地址设置为动态获取方式时,DHCP服务器就会根据DHCP协议给客户端分配IP,使得客户机能够利用这个IP上网。
*/

namespace GetAndSetIpAddressDemo
{
    public partial class FormGetAndSetIP : Form
    {
        public FormGetAndSetIP()
        {
            InitializeComponent();
        }

        private void FormGetAndSetIP_Load(object sender, EventArgs e)
        {
            cboLocalIP.Items.Clear();//清空本地连接IP列表
            cboWirelessIP.Items.Clear();//清空无线网络连接IP列表
            ManagementClass managementClass = new ManagementClass("Win32_NetWorkAdapterConfiguration");
            ManagementObjectCollection managementObjectCollection = managementClass.GetInstances();
            foreach (ManagementObject managementObject in managementObjectCollection)
            {
                if (Convert.ToBoolean(managementObject["IPEnabled"]))
                {
                    if (managementObject["IPAddress"] != null)
                    {
                        DisplayInfo($"本地计算机所有网卡信息:【{managementObject["Description"]}】");
                    }
                    PropertyDataCollection propertyDataCollection = managementObject.Properties;
                    foreach (PropertyData propertyData in propertyDataCollection)
                    {
                        object val = propertyData.Value;
                        //如果是字符串数组
                        if (propertyData.IsArray)
                        {
                            if (val is string[])
                                val = string.Join(",", val as string[]);
                            else if (val is ushort[])
                                val = string.Join(",", val as ushort[]);
                            else if (val is uint[])
                                val = string.Join(",", val as uint[]);
                        }
                        //通用信息模型(CIM,Common Information Model)
                        //限定符信息:一般为CimType信息
                        List<string> listQualifier = new List<string>();
                        foreach (QualifierData qualifierData in propertyData.Qualifiers)
                        {
                            listQualifier.Add($"[{qualifierData.Name}:{qualifierData.Value}]");
                        }
                        DisplayInfo($"Name:【{propertyData.Name}】,Value:【{val}】,Type:【{propertyData.Type}】,IsArray:【{propertyData.IsArray}】,Qualifier:【{string.Join(",", listQualifier)}】");
                    }
                }
            }
            DataTable dataTable = new DataTable("NetInterfaces");
            dataTable.Columns.Add("编号", typeof(int));
            dataTable.Columns.Add("网络适配器名称", typeof(string));
            dataTable.Columns.Add("正在被使用", typeof(bool));
            dataTable.Columns.Add("操作状态", typeof(string));
            dataTable.Columns.Add("接口类型", typeof(string));
            dataTable.Columns.Add("标识符", typeof(string));
            dataTable.Columns.Add("媒体访问控制(MAC)", typeof(string));
            dataTable.Columns.Add("接口速度(位每秒)", typeof(long));
            dataTable.Columns.Add("接口说明", typeof(string));
            dataTable.Columns.Add("支持IPv4协议", typeof(bool));
            dataTable.Columns.Add("支持IPv6协议", typeof(bool));
            dataTable.Columns.Add("IP地址集合", typeof(string));
            int count = 0;
            foreach (NetworkInterface netInterface in NetworkInterface.GetAllNetworkInterfaces())
            {
                count++;
                DisplayInfo($"第【{count}】个网络接口名:{netInterface.Name}");
                //当前正在使用的网络接口。接口操作状态为up;
                //本地连接:接口类型为Ethernet以太网。 回环测试(127.0.0.1):接口类型为Loopback
                //本机的测试环境是Wireless:无线连接
                if (netInterface.OperationalStatus == OperationalStatus.Up)
                {
                    DisplayInfo($"--该网络接口正在被使用...");
                }
                DisplayInfo($"    当前操作状态:{netInterface.OperationalStatus}");
                DisplayInfo($"    网络接口类型:{netInterface.NetworkInterfaceType}");
                DisplayInfo($"    网络适配器的标识符:{netInterface.Id}");
                DisplayInfo($"    接口MAC:{netInterface.GetPhysicalAddress()}");//MAC:媒体访问控制,介质访问控制(Medium Access Control)
                DisplayInfo($"    接口速度(位每秒,bitwise/s):{netInterface.Speed}");
                DisplayInfo($"    接口描述信息:{netInterface.Description}");
                DisplayInfo($"    是否支持IPv4协议:{netInterface.Supports(NetworkInterfaceComponent.IPv4)}");
                DisplayInfo($"    是否支持IPv6协议:{netInterface.Supports(NetworkInterfaceComponent.IPv6)}");
                DisplayInfo($"    接口配置的IP地址:");
                List<string> listAddresses = new List<string>();
                foreach (UnicastIPAddressInformation ipIntProp in netInterface.GetIPProperties().UnicastAddresses.ToArray<UnicastIPAddressInformation>())
                {
                    listAddresses.Add($"IP:【{ipIntProp.Address}】,类型:【{ipIntProp.Address.AddressFamily}】");
                    DisplayInfo($"        IP:【{ipIntProp.Address}】,类型:【{ipIntProp.Address.AddressFamily}】");
                    if (netInterface.NetworkInterfaceType == NetworkInterfaceType.Ethernet && ipIntProp.Address.AddressFamily == AddressFamily.InterNetwork)
                    {
                        cboLocalIP.Items.Add(ipIntProp.Address.ToString());
                    }
                    else if (netInterface.NetworkInterfaceType == NetworkInterfaceType.Wireless80211 && ipIntProp.Address.AddressFamily == AddressFamily.InterNetwork)
                    {
                        cboWirelessIP.Items.Add(ipIntProp.Address.ToString());
                    }
                }
                dataTable.Rows.Add(count, netInterface.Name, netInterface.OperationalStatus == OperationalStatus.Up, netInterface.OperationalStatus, netInterface.NetworkInterfaceType, netInterface.Id, netInterface.GetPhysicalAddress(),
                    netInterface.Speed, netInterface.Description, netInterface.Supports(NetworkInterfaceComponent.IPv4), netInterface.Supports(NetworkInterfaceComponent.IPv6), string.Join(";", listAddresses));
            }

            List<Tuple<string, string>> tuples = new List<Tuple<string, string>>()
            {
                Tuple.Create("编号", "编号"),
                Tuple.Create("网络适配器名称", "网络适配器名称"),
                Tuple.Create("正在被使用", "正在被使用"),
                Tuple.Create("操作状态", "操作状态"),
                Tuple.Create("接口类型", "接口类型"),
                Tuple.Create("标识符", "标识符"),
                Tuple.Create("媒体访问控制(MAC)", "媒体访问控制(MAC)"),
                Tuple.Create("接口速度(位每秒)", "接口速度(位每秒)"),
                Tuple.Create("接口说明", "接口说明"),
                Tuple.Create("支持IPv4协议", "支持IPv4协议"),
                Tuple.Create("支持IPv6协议", "支持IPv6协议"),
                Tuple.Create("IP地址集合", "IP地址集合")
            };
            SetDataGridViewColumns(tuples);
            dgvIpList.DataSource = dataTable;
        }

        /// <summary>
        /// 数据网格绑定列配置
        /// </summary>
        /// <param name="tuples"></param>
        private void SetDataGridViewColumns(List<Tuple<string, string>> tuples)
        {
            dgvIpList.AutoGenerateColumns = false;
            for (int i = 0; i < tuples.Count; i++)
            {
                string columnName = tuples[i].Item1;
                string columnDescription = tuples[i].Item2;
                int minWidth = 50;
                DataGridViewColumn dgvc = new DataGridViewColumn();
                dgvc.CellTemplate = new DataGridViewTextBoxCell();
                dgvc.Name = "dgvc_" + columnName;
                dgvc.MinimumWidth = minWidth;
                dgvc.DataPropertyName = columnName;
                dgvc.HeaderText = (columnDescription == null || columnDescription.Trim().Length == 0) ? columnName : columnDescription;
                dgvIpList.Columns.Add(dgvc);
            }
        }

        /// <summary>
        /// 显示文本框的消息
        /// </summary>
        /// <param name="message"></param>
        private void DisplayInfo(string message)
        {
            this.BeginInvoke(new Action(() =>
            {
                if (rtxbResult.TextLength >= 204800)
                {
                    rtxbResult.Clear();
                }
                rtxbResult.AppendText($"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")} --> {message}\n");
                rtxbResult.ScrollToCaret();
            }));
        }

        private void btnConfirm_Click(object sender, EventArgs e)
        {
            ManagementClass managementClass = new ManagementClass("Win32_NetWorkAdapterConfiguration");
            ManagementObjectCollection managementObjectCollection = managementClass.GetInstances();
            foreach (ManagementObject managementObject in managementObjectCollection)
            {
                if (Convert.ToBoolean(managementObject["IPEnabled"]))
                {
                    ManagementBaseObject newIP = managementObject.GetMethodParameters("EnableStatic");
                    ManagementBaseObject newGateway = managementObject.GetMethodParameters("SetGateways");
                    ManagementBaseObject newDNS = managementObject.GetMethodParameters("SetDNSServerSearchOrder");
                    //目标IP地址:
                    newIP["IPAddress"] = new string[] { txtIPAddress.Text.Trim() };
                    //子网掩码:
                    newIP["SubnetMask"] = new string[] { txtSubnetMask.Text.Trim() };
                    //默认网关:
                    newGateway["DefaultIPGateway"] = new string[] { txtDefaultGateway.Text.Trim() };
                    newGateway["GatewayCostMetric"] = new int[] { 1 };
                    // 将要修改的目标  首选DNS服务器
                    // 将要修改的目标  备用DNS服务器
                    newDNS["DNSServerSearchOrder"] = new string[] { txtFirstDNS.Text.Trim(), txtSpareDNS.Text.Trim() };
                    // 修改网络设置
                    try
                    {
                        if (rdoAutoSetIP.Checked)
                        {
                            managementObject.InvokeMethod("EnableStatic", null);
                            //重置DNS为空
                            managementObject.InvokeMethod("SetDNSServerSearchOrder", null);
                            //开启DHCP
                            managementObject.InvokeMethod("EnableDHCP", null);
                            MessageBox.Show("自动获取IP成功!");
                        }
                        else
                        {
                            ManagementBaseObject setIP = managementObject.InvokeMethod("EnableStatic", newIP, null);
                            ManagementBaseObject setGateways = managementObject.InvokeMethod("SetGateways", newGateway, null);
                            ManagementBaseObject setDNS = managementObject.InvokeMethod("SetDNSServerSearchOrder", newDNS, null);
                            MessageBox.Show("手动设置IP成功");
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message, "设置IP时出现异常");
                    }
                    break;
                }
            }
        }

        /// <summary>
        /// 重新读取按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnReload_Click(object sender, EventArgs e)
        {
            ManagementClass managementClass = new ManagementClass("Win32_NetWorkAdapterConfiguration");
            ManagementObjectCollection managementObjectCollection = managementClass.GetInstances();
            foreach (ManagementObject managementObject in managementObjectCollection)
            {
                if (Convert.ToBoolean(managementObject["IPEnabled"]))
                {
                    DisplayInfo($" Caption:{managementObject["Caption"]}\n ServiceName:{managementObject["ServiceName"]}\n MACAddress:{managementObject["MACAddress"]}");
                    rdoAutoSetIP.Checked = Convert.ToBoolean(managementObject["DHCPEnabled"]);
                    rdoManualSetIP.Checked = !Convert.ToBoolean(managementObject["DHCPEnabled"]);

                    string[] ipaddresses = (string[])managementObject["IPAddress"];
                    string[] subnets = (string[])managementObject["IPSubnet"];
                    string[] gateways = (string[])managementObject["DefaultIPGateway"];
                    string[] dnsSetting = (string[])managementObject["DNSServerSearchOrder"];

                    txtIPAddress.Text = ipaddresses[0];
                    txtSubnetMask.Text = subnets[0];
                    txtSubnetMask.Text = gateways[0];

                    if (dnsSetting.Length > 0)
                    {
                        txtFirstDNS.Text = dnsSetting[0];
                    }
                    if (dnsSetting.Length > 1)
                    {
                        txtSpareDNS.Text = dnsSetting[1];
                    }

                    rdoAutoSetIP_CheckedChanged(null, e);
                    break;
                }
            }
        }

        /// <summary>
        /// 自动获取IP和手动设置IP的单选按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void rdoAutoSetIP_CheckedChanged(object sender, EventArgs e)
        {
            if (rdoAutoSetIP.Checked)
            {
                txtIPAddress.Clear();
                txtSubnetMask.Clear();
                txtDefaultGateway.Clear();
                pnlManualSetIP.Enabled = false;
            }
            else
            {
                pnlManualSetIP.Enabled = true;
            }
        }
    }
}

程序运行如图:

C#获取本机网络连接名,获取和设置IP地址

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://bianchenghao.cn/38993.html

(0)
编程小号编程小号

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注