您可以使用 .Net NetworkInterface
(和相关)类获取网络适配器的接口索引。
这是一个代码示例:
static void PrintInterfaceIndex(string adapterName)
{
NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
IPGlobalProperties properties = IPGlobalProperties.GetIPGlobalProperties();
Console.WriteLine("IPv4 interface information for {0}.{1}",
properties.HostName, properties.DomainName);
foreach (NetworkInterface adapter in nics)
{
if (adapter.Supports(NetworkInterfaceComponent.IPv4) == false)
{
continue;
}
if (!adapter.Description.Equals(adapterName, StringComparison.OrdinalIgnoreCase))
{
continue;
}
Console.WriteLine(adapter.Description);
IPInterfaceProperties adapterProperties = adapter.GetIPProperties();
IPv4InterfaceProperties p = adapterProperties.GetIPv4Properties();
if (p == null)
{
Console.WriteLine("No information is available for this interface.");
continue;
}
Console.WriteLine(" Index : {0}", p.Index);
}
}
然后只需使用您的网络适配器的名称调用此函数:
PrintInterfaceIndex("your network adapter name");
您还可以使用Win32_NetworkAdapter
WMI 类获取网络适配器的 InterfaceIndex。该类Win32_NetworkAdapter
包含一个名为 InterfaceIndex 的属性。
因此,要检索具有给定名称的网络适配器的 InterfaceIndex,请使用以下代码:
ManagementScope scope = new ManagementScope("\\\\.\\ROOT\\cimv2");
ObjectQuery query = new ObjectQuery("SELECT * FROM Win32_NetworkAdapter WHERE Description='<Your Network Adapter name goes here>'");
using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query))
{
using (ManagementObjectCollection queryCollection = searcher.Get())
{
foreach (ManagementObject mo in queryCollection)
{
Console.WriteLine("InterfaceIndex : {0}, name {1}", mo["InterfaceIndex"], mo["Description"]);
}
}
}
如果您不想使用 WMI,也可以将 Win32 API 函数
GetAdaptersInfo与IP_ADAPTER_INFO
结构结合使用。您将在pinvoke.net找到一个示例。