如何获得网络适配器索引?

时间:2012-06-21 18:57:25

标签: c# windows networking routing

从代码中我想强制Windows机器使用特定的网络适配器来连接到特定IP地址的所有连接。

我计划使用ROUTE ADD命令行工具,但这要求我事先知道网络适配器的索引号(因为它必须提供给ROUTE ADD命令)

问题:如果我知道它的名字,我怎样才能以编程方式检索网络适配器的索引?

我知道ROUTE PRINT向我显示了我需要的信息(所有网络适配器的索引号),但是必须有一种方法来以编程方式获取该信息(C#)?

请注意,我不喜欢解析ROUTE PRINT的文本输出,因为文本格式可能会随着不同的Windows版本而改变。

2 个答案:

答案 0 :(得分:10)

您可以获取网络适配器的接口索引 使用.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");

您还可以获取网络适配器的InterfaceIndex 使用Win32_NetworkAdapter WMI类。 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函数 GetAdaptersInfoIP_ADAPTER_INFO结构相结合。 你会在这里找到一个例子pinvoke.net

答案 1 :(得分:0)

您是否考虑过使用C#的system.net.networkinformation接口?

http://msdn.microsoft.com/en-us/library/system.net.networkinformation.networkinterface.getallnetworkinterfaces.aspx

我不熟悉ROUTE ADD,但理论上你可以将信息与其他信息结合起来。

相关问题