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.
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.
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With