简体   繁体   中英

How do you determine which adapter is used?

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 (ie wireless, lan, etc) on my machine, which card is being used for the connection?

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

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.

你为什么不使用MAC地址?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM