Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Identifying active network interface

Tags:

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.

like image 502
Tiberiu Ana Avatar asked Dec 11 '08 14:12

Tiberiu Ana


People also ask

How can I tell which network interface is being used?

Open up the Task Manager, go to the Networking tab, and you can see which adapters are being utilized. Show activity on this post. You can identify the adapter by MAC address (Physical Address) using the ipconfig /all command.

How do I find network interface in Linux?

The best way to check the network interface in Linux is to use the ifconfig command. To do this, simply open a terminal and type “ifconfig -a”. This will return a list of all available network interfaces on your system.


1 Answers

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

like image 135
Yariv Avatar answered Sep 20 '22 17:09

Yariv