在C#中查找接口索引

akr*_*roy 5 .net c# network-programming

如何在C#中获取连接的interace索引?

如果索引不是标准术语,我的意思是与接口关联的数字,例如当您使用命令"netsh int ipv4 show int"按左侧的索引列出您的连接时.它也用于"路由添加[网关]掩码[索引]如果[接口索引]".

我知道接口的名称和描述,所以使用NetworkInterface.GetAllNetworkInterfaces()然后找到合适的接口是相当直接的.从那里,我找不到索引.我认为ID可能是相同的,但它具有"{XXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}"形式的值,而不是小整数值.

Eli*_*ing 8

我想你想要的

myInterface.GetIPProperties().GetIPv4Properties().Index;
Run Code Online (Sandbox Code Playgroud)

如在

var interfaces = NetworkInterface.GetAllNetworkInterfaces(); 

foreach(var @interface in interfaces)
{
    var ipv4Properties = @interface.GetIPProperties().GetIPv4Properties();

    if (ipv4Properties != null)
        Console.WriteLine(ipv4Properties.Index);
}
Run Code Online (Sandbox Code Playgroud)

请注意,如果没有可用于该接口的IPv4信息,则GetIPv4Properties()可以返回null.

这个msdn页面显示了一个可能有用的示例.