C#中获取本机IP地址,子网掩码,网关地址
首先添加对程序集System.Management的引用
- using System;
- using System.Management;
- namespace ConsoleApplication1
- {
- class Program
- {
- static void Main(string[] args)
- {
- ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
- ManagementObjectCollection nics = mc.GetInstances();
- foreach (ManagementObject nic in nics)
- {
- if (Convert.ToBoolean(nic["ipEnabled"]) == true)
- {
- Console.WriteLine((nic["IPAddress"] as String[])[0]);
- Console.WriteLine((nic["IPSubnet"] as String[])[0]);
- Console.WriteLine((nic["DefaultIPGateway"] as String[])[0]);
- }
- }
- }
- }
- }