14

コードから、特定のIPアドレスへのすべての接続に特定のネットワークアダプターを使用するようにWindowsマシンに強制したいと思います。

ROUTE ADDコマンドラインツールを使用してこれを行う予定ですが、これには、ネットワークアダプタのインデックス番号を事前に知っている必要があります(ROUTE ADDコマンドに指定する必要があるため)。

質問:名前がわかっている場合、ネットワークアダプタのインデックスをプログラムで取得するにはどうすればよいですか?

ROUTE PRINTに必要な情報(存在するすべてのネットワークアダプターのインデックス番号)が表示されることは知っていますが、プログラムでその情報を取得する方法も必要ですか(C#)?

テキスト形式はWindowsのバージョンによって異なる可能性があるため、ROUTEPRINTからのテキスト出力を解析するのは好きではないことに注意してください。

4

2 に答える 2

12

NetworkInterface.Net (および関連する)クラスを使用して、ネットワークアダプタのインターフェイスインデックスを取得できます。

コード例は次のとおりです。

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_NetworkAdapterWMIクラスを使用して、ネットワークアダプターの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を使用したくない場合は、Win32API関数 GetAdaptersInfoを構造体と組み合わせて使用​​することもできますIP_ADAPTER_INFO。ここに例がありますpinvoke.net

于 2012-06-21T20:17:11.737 に答える
0

C#のsystem.net.networkinformationインターフェースの使用を検討しましたか?

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

私はROUTEADDに精通していませんが、理論的には一方から他方への情報を組み合わせることができます。

于 2012-06-21T19:12:44.920 に答える