根据
MSDN页面关于
NetworkInterface.NetworkInterfaceType
属性的说明,该属性仅返回在NetworkInterfaceType枚举中定义的一部分可能值。可能的值包括以下内容:Ethernet Fddi Loopback Ppp Slip TokenRing Unknown。
因此,您可能会遇到确定性问题。
但是,您可以对可用的网络连接执行一些启发式操作,以确定它们是WiFi还是电缆连接。这些可能包括在多个迭代中进行的ping响应/延迟时间等。
此外,适配器的速度可能作为提示使用。对于我的WiFi适配器,速度始终显示为“54000000”(例如54 mbs)。由于存在一组常见的WiFi速度,因此这可能有所帮助。
也许以下代码可以帮助您入门:
using System;
using System.Net.NetworkInformation;
using System.Net;
namespace ConsoleApplication7
{
class Program
{
static void Main(string[] args)
{
NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces();
Ping pingObj = new Ping();
for (int i = 0; i < adapters.Length; i++)
{
Console.WriteLine("Network adapter: {0}", adapters[i].Name);
Console.WriteLine(" Status: {0}", adapters[i].OperationalStatus.ToString());
Console.WriteLine(" Interface: {0}", adapters[i].NetworkInterfaceType.ToString());
Console.WriteLine(" Description: {0}", adapters[i].Description);
Console.WriteLine(" ID: {0}", adapters[i].Id);
Console.WriteLine(" Speed: {0}", adapters[i].Speed);
Console.WriteLine(" SupportsMulticast: {0}", adapters[i].SupportsMulticast);
Console.WriteLine(" IsReceiveOnly: {0}", adapters[i].IsReceiveOnly);
Console.WriteLine(" MAC: {0}", adapters[i].GetPhysicalAddress().ToString());
if (adapters[i].NetworkInterfaceType != NetworkInterfaceType.Loopback)
{
IPInterfaceProperties IPIP = adapters[i].GetIPProperties();
if (IPIP != null)
{
bool bGateWayReachable = false;
foreach (GatewayIPAddressInformation gw in IPIP.GatewayAddresses)
{
Console.WriteLine(" Gateway: {0} - ", gw.Address.ToString());
PingReply pr = pingObj.Send(gw.Address, 2000);
if (pr.Status == IPStatus.Success)
{
Console.WriteLine(" reachable ({0}ms)", pr.RoundtripTime);
bGateWayReachable = true;
break;
}
else
Console.WriteLine(" NOT reachable");
}
if (bGateWayReachable == true)
{
foreach (IPAddress ipDNS in IPIP.DnsAddresses)
{
Console.WriteLine(" DNS: {0} - ", ipDNS.ToString());
PingReply pr = pingObj.Send(ipDNS, 5000);
if (pr.Status == IPStatus.Success)
{
Console.WriteLine(" reachable ({0}ms)", pr.RoundtripTime);
Console.WriteLine(" --- SUCCESS ---");
break;
}
else
Console.WriteLine(" NOT reachable");
}
}
}
}
}
Console.ReadLine();
}
}
}