C# System.Net.NetworkInformation获取网络相关信息
using System.Net.Sockets; namespace Demo.NetworkInformation { internal class Program { private enum IpAddressType { Ipv4, Ipv6, Other } static void Main(string[] args) { NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces();//获取本地计算机上网络接口的对象 Console.WriteLine($"适配器个数:\t{adapters.Length}" ); Console.WriteLine(); foreach (NetworkInterface adapter in adapters) { if (adapter.NetworkInterfaceType == NetworkInterfaceType.Ethernet || adapter.NetworkInterfaceType == NetworkInterfaceType.GigabitEthernet) { Console.WriteLine($"描述:\t\t{adapter.Description}"); Console.WriteLine($"标识符:\t{adapter.Id}"); Console.WriteLine($"名称:\t\t{adapter.Name}"); Console.WriteLine($"类型:\t\t{adapter.NetworkInterfaceType}"); Console.WriteLine($"速度:\t\t{adapter.Speed * 0.001 * 0.001 + "M"}"); Console.WriteLine($"状态:\t\t{adapter.OperationalStatus}"); Console.WriteLine($"MAC 地址:\t{adapter.GetPhysicalAddress()}"); Console.WriteLine("-----------------------------------------------"); foreach (var item in adapter.GetIPProperties().UnicastAddresses) { Console.WriteLine($"{GetIpAddressType(item.Address)}地址:\t{item.Address}"); Console.WriteLine($"子网掩码:\t{item.IPv4Mask}"); } foreach (var item in adapter.GetIPProperties().GatewayAddresses) { Console.WriteLine($"{GetIpAddressType(item.Address)}网关:\t{item.Address}"); } foreach (var item in adapter.GetIPProperties().DnsAddresses) { Console.WriteLine($"DNS:\t\t{item}"); } Console.WriteLine(); } } Console.ReadKey(); } private static IpAddressType GetIpAddressType(IPAddress iPAddress) { switch (iPAddress.AddressFamily) { case AddressFamily.InterNetwork: { return IpAddressType.Ipv4; } case AddressFamily.InterNetworkV6: { return IpAddressType.Ipv6; } default: { return IpAddressType.Other; } } } } }