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_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を使用したくない場合は、Win32API関数
GetAdaptersInfoを構造体と組み合わせて使用することもできますIP_ADAPTER_INFO
。ここに例がありますpinvoke.net。