获取本地通用网卡信息是一个非常常见的需求,C#提供了System.Net.NetworkInformation命名空间下的NetworkInterface类来实现该功能。下面我们来详细讲解如何获得本地通用网卡信息的示例代码:
1.获取本地所有网卡信息
使用NetworkInterface类可以获取本地所有网卡信息,示例代码如下:
using System.Net.NetworkInformation;
NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface n in interfaces)
{
Console.WriteLine("=============");
Console.WriteLine("Name: {0}", n.Name);
Console.WriteLine("Description: {0}", n.Description);
Console.WriteLine("Type: {0}", n.NetworkInterfaceType);
Console.WriteLine("Speed: {0}", n.Speed);
Console.WriteLine("MAC: {0}", n.GetPhysicalAddress());
Console.WriteLine("Is Receive Only: {0}", n.IsReceiveOnly);
Console.WriteLine("Is Up: {0}", n.OperationalStatus == OperationalStatus.Up);
}
在上述代码中,我们通过调用NetworkInterface.GetAllNetworkInterfaces()
方法获取本地所有网卡信息,然后使用foreach遍历所有网卡。接着我们打印每个网卡的Name、Description、NetworkInterfaceType、Speed、MAC等信息。
2.获取本地默认网关对应的网卡信息
本地默认网关是指没有指定目标地址时,操作系统所选用的默认出口网关。我们可以通过获取本地默认路由来获得本地默认网关的IP地址,然后通过IP地址获取对应的网卡信息,示例代码如下:
using System.Net;
using System.Net.NetworkInformation;
IPAddress gateway = null;
NetworkInterface gatewayInterface = null;
foreach (NetworkInterface n in NetworkInterface.GetAllNetworkInterfaces())
{
IPInterfaceProperties ipProps = n.GetIPProperties();
foreach (GatewayIPAddressInformation gatewayAddr in ipProps.GatewayAddresses)
{
if (gatewayAddr.Address.AddressFamily == AddressFamily.InterNetwork)
{
gateway = gatewayAddr.Address;
gatewayInterface = n;
break;
}
}
if (gateway != null) break;
}
Console.WriteLine("Default Gateway: {0}", gateway.ToString());
Console.WriteLine("Default Gateway Interface:");
Console.WriteLine("Description: {0}", gatewayInterface.Description);
Console.WriteLine("Name: {0}", gatewayInterface.Name);
Console.WriteLine("Type: {0}", gatewayInterface.NetworkInterfaceType);
Console.WriteLine("Speed: {0}", gatewayInterface.Speed);
Console.WriteLine("MAC: {0}", gatewayInterface.GetPhysicalAddress());
Console.WriteLine("Is Receive Only: {0}", gatewayInterface.IsReceiveOnly);
Console.WriteLine("Is Up: {0}", gatewayInterface.OperationalStatus == OperationalStatus.Up);
在上述代码中,我们首先通过遍历所有网卡的GatewayAddresses属性,找到本地默认网关对应的IP地址。接着遍历所有网卡,找到对应默认网关的网卡信息。最后打印对应网卡的Name、Description、NetworkInterfaceType、Speed、MAC等信息。
这两个示例代码可以帮助开发者了解如何使用C#来获取本地通用网卡信息。根据实际需要,开发者可以进一步修改代码,以满足自己的需求。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:C# 获得本地通用网卡信息的示例代码 - Python技术站