C# 读取本地网络配置信息
|
admin
2024年12月3日 20:52
本文热度 2467
|
在 C# 中,您可以使用 System.Net.NetworkInformation 命名空间来读取本地网络配置信息。这可以包括获取网络适配器的状态、IP 地址、子网掩码、网关等信息。以下是如何实现这一功能的详细步骤和示例代码。
1. 引入命名空间
确保您在代码文件中包含以下命名空间:
using System;using System.Net.NetworkInformation;using System.Net;
2. 读取网络配置信息
以下示例代码展示了如何读取并显示本地网络配置信息:
class Program{ static void Main(string[] args) { // 获取本地网络适配器的信息 NetworkInterface[] networkInterfaces = NetworkInterface.GetAllNetworkInterfaces(); foreach (NetworkInterface networkInterface in networkInterfaces) { Console.WriteLine($"网络适配器名称: {networkInterface.Name}"); Console.WriteLine($"描述: {networkInterface.Description}"); Console.WriteLine($"类型: {networkInterface.NetworkInterfaceType}"); Console.WriteLine($"状态: {networkInterface.OperationalStatus}"); Console.WriteLine($"MAC 地址: {networkInterface.GetPhysicalAddress()}"); // 获取 IP 地址信息 IPInterfaceProperties ipProperties = networkInterface.GetIPProperties(); // 获取 IPv4 地址 foreach (var unicast in ipProperties.UnicastAddresses) { if (unicast.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) { Console.WriteLine($"IPv4 地址: {unicast.Address}"); Console.WriteLine($"子网掩码: {unicast.IPv4Mask}"); } } // 获取网关 foreach (var gateway in ipProperties.GatewayAddresses) { if (gateway.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) { Console.WriteLine($"默认网关: {gateway.Address}"); } } Console.WriteLine("------------------------------------"); } Console.WriteLine("按任意键退出..."); Console.ReadKey(); }}
代码解析 获取网络适配器信息: 使用 NetworkInterface.GetAllNetworkInterfaces() 获取系统中的所有网络适配器。 遍历每个适配器: 输出适配器的名称、描述、类型和状态。 获取 IP 配置: 使用 GetIPProperties() 方法获取适配器的 IP 地址属性。 输出 IPv4 地址和子网掩码: 遍历 UnicastAddresses 列表,并检查地址类型是否为 IPv4。 获取并输出默认网关: 遍历 GatewayAddresses 列表,获取默认网关的信息。
3. 运行程序
将上述代码复制到新的 C# 控制台应用程序中并运行。当程序执行时,它将列出本地计算机中所有网络适配器的配置信息。
注意事项
确保您有足够的权限来访问网络配置信息,某些网络设置可能需要管理员权限。
如果在没有网络连接的情况下运行程序,可能会看到部分或没有信息。
总结
使用 System.Net.NetworkInformation 命名空间,您可以轻松读取并显示计算机的网络配置信息。这对网络监控、调试和其他应用场景非常有用。通过进一步扩展代码,您可以将更多的相关信息提取并利用。
该文章在 2024/12/4 15:17:24 编辑过