5

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.

Cannoliopsida
  • 3,044
  • 5
  • 36
  • 61

4 Answers4

8

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.

Elian Ebbing
  • 18,779
  • 5
  • 48
  • 56
  • This can only be a half solution, since all interface must have a index, while it doesn't necessarily have a ip address. esp, when the iface is down... – Ben Mar 28 '21 at 16:56
1

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;
}
}
Community
  • 1
  • 1
John Mitchell
  • 9,653
  • 9
  • 57
  • 91
0

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

0

I updated Elian Ebbing's answer to get just the adapters that support IPv4:

  IEnumerable<KeyValuePair<int, NetworkInterface>> GetNetworkInterfaces()
  {
     foreach (var networkInterface in NetworkInterface.GetAllNetworkInterfaces())
     {
        IPv4InterfaceProperties properties = null;
        try { properties = networkInterface.GetIPProperties().GetIPv4Properties(); }
        catch (NetworkInformationException) { /* this one doesn't support IPv4 */ }

        if (properties != null)
           yield return new KeyValuePair<int, NetworkInterface>(properties.Index, networkInterface);
     }
  }

P.S. Since there are exceptions involved, this code may be slow. I recommend constructing a lookup from the sequence returned by this method, and re-using it until NetworkChange.NetworkAddressChanged event is raised.

GregC
  • 7,737
  • 2
  • 53
  • 67