Identifying active network interface
The simplest way would be:
UdpClient u = new UdpClient(remoteAddress, 1);
IPAddress localAddr = ((IPEndPoint)u.Client.LocalEndPoint).Address;
Now, if you want the NetworkInterface object you do something like:
foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
{
IPInterfaceProperties ipProps = nic.GetIPProperties();
// check if localAddr is in ipProps.UnicastAddresses
}
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 the IPv4InterfaceProperties.Index
property).
Neither of these will actually give the OP the info he's looking for -- he wants to know which interface will be used to reach a given destination. One way of doing what you want would be to shell out to the route command using System.Diagnostics.Process class, then screen-scrape the output. route PRINT (destination IP)
will get you something useable. That's probably not the best solution, but it's the only one I can give you right now.
The info you are after will be in WMI.
This example using WMI may get you most of the way:
using System.Management;
string query = "SELECT * FROM Win32_NetworkAdapterConfiguration";
ManagementObjectSearcher moSearch = new ManagementObjectSearcher(query);
ManagementObjectCollection moCollection = moSearch.Get();// Every record in this collection is a network interface
foreach (ManagementObject mo in moCollection)
{
// Do what you need to here....
}
The Win32_NetworkAdapterConfiguration class will give you info about the configuration of your adapters e.g. ip addresses etc.
You can also query the Win32_NetworkAdapter class to find out 'static'about each adapter (max speed, manufacturer etc)
At least you can start with that, giving you all addresses from dns for the local machine.
IPHostEntry hostEntry = Dns.GetHostEntry(Environment.MachineName);
foreach (System.Net.IPAddress address in hostEntry.AddressList)
{
Console.WriteLine(address);
}