C# 获取IPV4地址,网关,子网掩码,网卡信息的方法

///这里是获取本机IPV4,网卡地址,网关,子网掩码

    ManagementClassmc = new ManagementClass("Win32_NetworkAdapterConfiguration");

                ManagementObjectCollection nics = mc.GetInstances();

                foreach (ManagementObjectnic in nics)

                {

                    if (Convert.ToBoolean(nic["ipEnabled"]) == true)

                    {

                     Console.WriteLine( (nic["IPAddress"] asString[])[0]);

                   Console.WriteLine( ["IPSubnet"] asString[])[0]);

                     Console.WriteLine( (nic["DefaultIPGateway"] asString[])[0]);

                    }

                }

           

////这个获取网卡一些信息

       NetworkInterface[] adapters =NetworkInterface.GetAllNetworkInterfaces();//获取本地计算机上网络接口的对象

               Console.WriteLine("适配器个数:" + adapters.Length);

               Console.WriteLine();

               foreach (NetworkInterfaceadapter in adapters)

               {

                   Console.WriteLine("描述:" +adapter.Description);

                   Console.WriteLine("标识符:" + adapter.Id);

                   Console.WriteLine("名称:" + adapter.Name);

                   Console.WriteLine("类型:" +adapter.NetworkInterfaceType);

                   Console.WriteLine("速度:" + adapter.Speed *0.001 * 0.001 + "M");

                   Console.WriteLine("操作状态:" + adapter.OperationalStatus);

                   Console.WriteLine("MAC 地址:" +adapter.GetPhysicalAddress());

 

                   // 格式化显示MAC地址              

                   PhysicalAddresspa = adapter.GetPhysicalAddress();//获取适配器的媒体访问(MAC)地址

                   byte[] bytes =pa.GetAddressBytes();//返回当前实例的地址

                   StringBuilder sb = newStringBuilder();

                   for (int i = 0; i

                   {

                       sb.Append(bytes[i].ToString("X2"));//以十六进制格式化

                       if (i != bytes.Length- 1)

                       {

                           sb.Append("-");

                       }

                   }

                   Console.WriteLine("MAC 地址:" + sb);

                   Console.WriteLine();

               }

你可能感兴趣的:(技术)