From code I want to force a Windows machine to use a specific network adapter for all connections to a specific IP address.
I plan to do so by using the ROUTE ADD command line tool, but this requires that I know in advance the network adapters' index number (as it must be given to the ROUTE ADD command).
QUESTION: How can I programmatically retrieve a network adapter's index, given I know its name?
I'm aware that ROUTE PRINT shows me the information I need (the index numbers of all network adapters present), but there must be a way to get that information programmatically too (C#)?
Note, that I don't like parsing the text output from ROUTE PRINT, as the text format may change with different Windows versions.
Best Answer
You can obtain the interface index of your network adapter by using the .Net
NetworkInterface
(and related) classes.Here is a code example:
Then just call this function with the name of your network adapter:
You can also obtain the InterfaceIndex of your network adapter by using the
Win32_NetworkAdapter
WMI class. TheWin32_NetworkAdapter
class contains a property called InterfaceIndex.So, to retrieve the InterfaceIndex for a network adapter with a given name, use the following code:
If you do not want to use WMI you could also use the Win32 API function GetAdaptersInfo in combination with the
IP_ADAPTER_INFO
struct. You will find an example here pinvoke.net.