|
本帖最后由 shiy720 于 2024-6-8 10:23 编辑
C# 中有多种方式可以获取网络适配器,以下是一些常见的方法:
使用 System.Net.NetworkInformation 命名空间
- using System.Net.NetworkInformation;
- NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces();
- foreach (NetworkInterface adapter in adapters)
- {
- Console.WriteLine(adapter.Name);
- Console.WriteLine(adapter.Description);
- Console.WriteLine(adapter.Speed); // 速度
- Console.WriteLine(adapter.GetPhysicalAddress()); // MAC 地址
- Console.WriteLine(adapter.GetIPProperties()); // IP 配置
- }
复制代码
使用 System.Management 命名空间
- using System.Management;
- ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_NetworkAdapter");
- foreach (ManagementObject adapter in searcher.Get())
- {
- Console.WriteLine(adapter["Name"]);
- Console.WriteLine(adapter["Description"]);
- Console.WriteLine(adapter["Speed"]); // 速度
- Console.WriteLine(adapter["MACAddress"]); // MAC 地址
- }
复制代码
使用 System.Net.Sockets 命名空间
- using System.Net.Sockets;
- IPHostEntry hostEntry = Dns.GetHostEntry(Dns.GetHostName());
- foreach (IPAddress address in hostEntry.AddressList)
- {
- Console.WriteLine(address.AddressFamily);
- Console.WriteLine(address.ToString());
- }
复制代码
使用 WMI (Windows Management Instrumentation)
- using System.Management;
- ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_NetworkAdapterConfiguration");
- foreach (ManagementObject adapter in searcher.Get())
- {
- Console.WriteLine(adapter["Caption"]);
- Console.WriteLine(adapter["Description"]);
- Console.WriteLine(adapter[" IPAddress"]); // IP 地址
- Console.WriteLine(adapter["DefaultIPGateway"]); // 默认网关
- Console.WriteLine(adapter["DNSDomain"]); // DNS 域
- }
复制代码
使用 System.Linq 和 System.Net.NetworkInformation 命名空间
- using System.Linq;
- using System.Net.NetworkInformation;
- NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces();
- var networkAdapters = adapters.Select(adapter => new
- {
- Name = adapter.Name,
- Description = adapter.Description,
- Speed = adapter.Speed,
- MacAddress = adapter.GetPhysicalAddress(),
- IpAddress = adapter.GetIPProperties().UnicastAddresses.FirstOrDefault().Address
- });
- foreach (var adapter in networkAdapters)
- {
- Console.WriteLine(adapter.Name);
- Console.WriteLine(adapter.Description);
- Console.WriteLine(adapter.Speed);
- Console.WriteLine(adapter.MacAddress);
- Console.WriteLine(adapter.IpAddress);
- }
复制代码
这些方法可以获取到网络适配器的基本信息,如名称、描述、速度、MAC 地址、IP 地址等。 |
|