In a .NET application, how can I identify which network interface is used to communicate to a given IP address?
I am running on workstations with multiple network interfaces, IPv4 and v6, and I need to get the address of the ‘correct’ interface used for traffic to my given database server.
The simplest way would be:
Now, if you want the NetworkInterface object you do something like:
Another option is to use P/Invoke and call GetBestInterface() to get the interface index, then again loop over all the network interfaces. As before, you’ll have to dig through
GetIPProperties()to get to theIPv4InterfaceProperties.Indexproperty).