检测正在使用的网络接口

时间:2015-09-12 16:50:28

标签: c# network-programming ip-address network-interface

我正在使用以下代码获取本地计算机的IPv4网关地址

var interfaces = System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces();
var wifi = interfaces[3];
var gatewayAddresses = wifi.GetIPProperties().GatewayAddresses;
var gateway = gatewayAddresses[0].Address.ToString();
IPv4GatewayValueLabel.Text = gateway;

工作正常,但我手动选择界面(活动的界面)。我想以编程方式选择它。

我做了一些调试。 NetworkInterface.GetAllNetworkInterfaces()返回接口列表。在我的例子中,有7个。我寻找一个区分活动界面和其他界面的属性,并找到了OperationalStatus,但它并不可靠。

我使用手机(wifi热点)连接到互联网,这是我得到的界面列表:

0:
    Description         "Microsoft Wi-Fi Direct Virtual Adapter"
    OperationalStatus   Down
1:
    Description         "Bluetooth Device (PAN)"
    OperationalStatus   Down
2:
    Description         "Realtek PCIe FE Family Controller"
    OperationalStatus   Down
3:
    Description         "Dell Wireless 1701 802.11b/g/n"
    OperationalStatus   Up
4:
    Description         "Software Loopback Interface 1"
    OperationalStatus   Up
5:
    Description         "Microsoft ISATAP Adapter"
    OperationalStatus   Down
6:
    Description         "Teredo Tunneling Pseudo-Interface"
    OperationalStatus   Down

如您所见,有两个Up值的接口。此外我不确定这个列表是否已修复,所以这次我使用usb tethering进行连接,界面列表略有改变:

0:
    Description         "SAMSUNG Mobile USB Remote NDIS Network Device"
    OperationalStatus   Up
1:
    Description         "Microsoft Wi-Fi Direct Virtual Adapter"
    OperationalStatus   Down
2:
    Description         "Bluetooth Device (PAN)"
    OperationalStatus   Down
3:
    Description         "Realtek PCIe FE Family Controller"
    OperationalStatus   Down
4:
    Description         "Dell Wireless 1701 802.11b/g/n"
    OperationalStatus   Down
5:
    Description         "Software Loopback Interface 1"
    OperationalStatus   Up
6:
    Description         "Teredo Tunneling Pseudo-Interface"
    OperationalStatus   Up
7:
    Description         "Microsoft ISATAP Adapter #2"
    OperationalStatus   Down

因此,我认为我不能依赖OperationalStatus。我怎样才能做到这一点?

2 个答案:

答案 0 :(得分:2)

你是在正确的路线上,可能已经想到了这一点,但这是我使用的,到目前为止它已经有效。我能想到的唯一问题是,如果有人使用的是其他vm软件,那么除了Hyper-V之外,我正专门寻找它。

NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface nic in nics)
{
  if (nic.NetworkInterfaceType != NetworkInterfaceType.Loopback 
      && nic.NetworkInterfaceType != NetworkInterfaceType.Tunnel
      && nic.OperationalStatus == OperationalStatus.Up 
      && nic.Name.StartsWith("vEthernet") == false 
      && nic.Description.Contains("Hyper-v") == false)
  {
    //Do something
    break;
  }
}

答案 1 :(得分:0)

也许在物理系统上(无法评论虚拟客户端),您还可以检查NetworkInterfaceTypeNetworkInterfaceType.Wireless80211& NetworkInterfaceType.Ethernet)以及OperationalStatus以查看哪个是一个真正的物理硬件适配器。

然而,我从来没有尝试过wifi无线电开启的配置。系统还连接到以太网电缆