3

I have a need to figure out which adapter is used when a connection is created. In other words, if I have multiple NIC cards (i.e. wireless, lan, etc) on my machine, which card is being used for the connection?

If anyone can point me in the right direction...

alex.davis.dev
  • 411
  • 7
  • 18
  • I've got no idea as to the answer, but it'll probably help seeing the code to create the connection. Also, is controlling the NIC the connection uses ok? – George Duckett Aug 25 '11 at 15:25
  • You are not going to be able to force your program to use a specfic connection. You should be able to determine which connection it is based on if a particular adapter is active. – Security Hound Aug 25 '11 at 15:27
  • possible duplicate of [Identifying active network interface in .NET](http://stackoverflow.com/questions/359596/identifying-active-network-interface-in-net) – Jehof Jan 09 '13 at 08:05

3 Answers3

4

In C#

foreach(var nic in NetworkInterface.GetAllNetworkInterfaces.Where(n => n.OperationalStatus == OperationStatus.UP)
{
    if(nic.GetIsNetworkAvailable())
    {
       //nic is attached to some form of network
    }
}

VB .NET

ForEach nic in NetworkInterface.GetAllNetworkInterfaces.Where(Function(n) n.OperationalStatus = OperationStatus.UP)
    If nic.GetIsNetworkAvailable() Then
       //nic is attached to some form of network
    End If
Next

This will only test active working Network Interfaces that are connected to an active network.

msarchet
  • 15,104
  • 2
  • 43
  • 66
  • As you note this only checks that the nic is attached to a network of some sort. I believe that http://stackoverflow.com/questions/359596/identifying-active-network-interface-in-net is a better solution. – Joshua Drake Jan 08 '13 at 20:00
0

Why don't you use the MAC address?

Rhyous
  • 6,510
  • 2
  • 44
  • 50
0

Maybe you could map it by the MAC Address:

var nics = NetworkInterface.GetAllNetworkInterfaces();
foreach (var nic in nics)
{
    if (nic.OperationalStatus == OperationalStatus.Up)
    {
        var mac = nic.GetPhysicalAddress().ToString();
        if (mac == "your:connections:mac:address")
        {
            /* ... */
        }
    }
}

The "your:connections:mac:address" part you can figure out following this method, using the IP address of the LocalEndPoint.

How do I obtain the physical (MAC) address of an IP address using C#?

It's not beautiful, but it could work.

Community
  • 1
  • 1
LueTm
  • 2,366
  • 21
  • 31