views:

1386

answers:

4

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.

+1  A: 

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)

Paul Nearney
+1  A: 

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);
}
BeowulfOF
+1  A: 

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.

Coderer
+2  A: 

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).

Yariv
after some research I'm finding that the "best" answer means:1. The first IP of the adapter with the matching route/default gateway combo with the lowest metric.2. In case of a metric tie, the adapter with the lowest binding order wins.
halr9000