如何确定使用哪个适配器?

时间:2011-08-25 15:21:15

标签: c# vb.net

我需要弄清楚创建连接时使用的适配器。换句话说,如果我的机器上有多个NIC卡(即无线,局域网等),哪个卡用于连接?

如果有人能指出我正确的方向......

3 个答案:

答案 0 :(得分:4)

在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

这将仅测试连接到活动网络的活动工作网络接口。

答案 1 :(得分:0)

为什么不使用MAC地址?

答案 2 :(得分:0)

也许您可以通过MAC地址映射它:

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")
        {
            /* ... */
        }
    }
}

“your:connections:mac:address”部分,您可以使用 LocalEndPoint 的IP地址来了解此方法。

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

它不漂亮,但它可以工作。

相关问题