Finding the interface index in C#

2019-06-26 16:53发布

How can I get the index of an interace for a connection in C#?

In case index isn't a standard term, I mean the number associated with an interface, such as when you use the command "netsh int ipv4 show int" to list your connections by index on the left. It's also used in "route add [gateway] mask [index] if [interface index]".

I know the name and description of the interface, so it's fairly straightfoward to use NetworkInterface.GetAllNetworkInterfaces() and then find the right one there. From there though, I can't find the index. I thought ID might be the same, but that has values of the form "{XXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}", not small integer values.

3条回答
Juvenile、少年°
2楼-- · 2019-06-26 17:22

All network interfaces are given a GUID which uniquely sets them apart and is used for individual manipulation in the Win environment that's what ID is.

The idx isn't directly assigned to the NIC but its used by the Windows Management System as a user firendly way of setting details .

Theres a snippet of code here which shows how to access the ManagementObjectSearcher which may contain the information, you would have to parse through the results (instead of just selecting name as below)

internal static IEnumerable<string> GetConnectedCardNames()
{
string query = String.Format(@"SELECT * FROM Win32_NetworkAdapter");
var searcher = new ManagementObjectSearcher
{
    Query = new ObjectQuery(query)
};

try
{
    log.Debug("Trying to select network adapters");
    var adapterObjects = searcher.Get();

    var names = (from ManagementObject o in adapterObjects
                    select o["Name"])
                        .Cast<string>();

    return names;
}
catch (Exception ex)
{
    log.Debug("Failed to get needed names, see Exception log for details");
    log.Fatal(ex);
    throw;
}
}
查看更多
Deceive 欺骗
3楼-- · 2019-06-26 17:32

I think you want

myInterface.GetIPProperties().GetIPv4Properties().Index;

As in

var interfaces = NetworkInterface.GetAllNetworkInterfaces(); 

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

    if (ipv4Properties != null)
        Console.WriteLine(ipv4Properties.Index);
}

Note that GetIPv4Properties() can return null if no IPv4 information is available for the interface.

This msdn page shows an example that might be helpful.

查看更多
Root(大扎)
4楼-- · 2019-06-26 17:32

Are you talking about the network adapter binding order? If so, that is normally stored in this registry key:

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\Tcpip\Linkage

查看更多
登录 后发表回答