winform C#如何获取本地计算机网卡信息---适用多网卡计算机
创建新的winform项目,命名为getMacIPmaskGateWay
在Form1窗体上添加一个textbox控件和button按钮
添加引用程序集
引入命名空间
using System.Management;
功能代码
ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration"); ManagementObjectCollection nics = mc.GetInstances(); foreach (ManagementObject nic in nics) { //循环获取本地计算机IP、MAC、Subnet、Default GateWay if (Convert.ToBoolean(nic["ipEnabled"]) == true) { try{ //当获取不到数据时,弹出异常 string mac = nic["MacAddress"].ToString();//Mac地址 string ip = (nic["IPAddress"] as String[])[0];//IP地址 string ipsubnet = (nic["IPSubnet"] as String[])[0];//子网掩码 string ipgateway = (nic["DefaultIPGateway"] as String[])[0];//默认网关 textBox1.Text += "IP地址 "+ip + "\r\n" +"MAC地址 "+ mac + "\r\n" + "子网掩码 "+ipsubnet + "\r\n" +"默认网关 "+ ipgateway + "\r\n" + "-----------------------------" + "\r\n"; } catch(Exception ee) { MessageBox.Show( ee.Message);//捕获异常信息 } } }
完整代码
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Management; namespace getMacIPmaskGateWay { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration"); ManagementObjectCollection nics = mc.GetInstances(); foreach (ManagementObject nic in nics) { //循环获取本地计算机IP、MAC、Subnet、Default GateWay if (Convert.ToBoolean(nic["ipEnabled"]) == true) { try{ //当获取不到数据时,弹出异常 string mac = nic["MacAddress"].ToString();//Mac地址 string ip = (nic["IPAddress"] as String[])[0];//IP地址 string ipsubnet = (nic["IPSubnet"] as String[])[0];//子网掩码 string ipgateway = (nic["DefaultIPGateway"] as String[])[0];//默认网关 textBox1.Text += "IP地址 "+ip + "\r\n" +"MAC地址 "+ mac + "\r\n" + "子网掩码 "+ipsubnet + "\r\n" +"默认网关 "+ ipgateway + "\r\n" + "-----------------------------" + "\r\n"; } catch(Exception ee) { MessageBox.Show( ee.Message); } } } } private void Form1_Load(object sender, EventArgs e) { button1.Text = "点击获取"; this.Text = "获取IP、MAC、Subnet、Default GateWay"; } } }
运行实现可获取本地计算机多个网卡的IP地址、MAC地址、子网掩码、默认网关信息
项目打包下载地址获取本地计算机网卡信息 提取密码 3guv
百家号 互联网微风说
微信公众号 weisico-com
转载请注明:微思考学习网-关注技术,分享知识 >> winform C#如何获取本地计算机IP地址,Mac地址,子网掩码,默认网关